Showing preview only (213K chars total). Download the full file or copy to clipboard to get everything.
Repository: sivaprasadreddy/Java-Persistence-with-MyBatis3
Branch: master
Commit: 29580704e196
Files: 126
Total size: 177.1 KB
Directory structure:
gitextract_ol89q38l/
├── .gitignore
├── README.md
├── chapter01/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ └── Student.java
│ │ │ ├── mappers/
│ │ │ │ └── StudentMapper.java
│ │ │ ├── services/
│ │ │ │ ├── JdbcStudentService.java
│ │ │ │ └── StudentService.java
│ │ │ └── util/
│ │ │ └── MyBatisSqlSessionFactory.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ └── StudentMapper.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── mybatis3/
│ │ └── services/
│ │ ├── StudentServiceTest.java
│ │ └── TestDataPopulator.java
│ └── resources/
│ └── log4j.properties
├── chapter02/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ └── Student.java
│ │ │ ├── mappers/
│ │ │ │ └── StudentMapper.java
│ │ │ ├── services/
│ │ │ │ └── StudentService.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ ├── DataSourceFactory.java
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ └── StudentMapper.xml
│ │ ├── full-mybatis-config.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── StudentServiceTest.java
│ └── TestDataPopulator.java
├── chapter03/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ ├── Address.java
│ │ │ │ ├── Course.java
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ ├── Student.java
│ │ │ │ └── Tutor.java
│ │ │ ├── mappers/
│ │ │ │ ├── AddressMapper.java
│ │ │ │ ├── CourseMapper.java
│ │ │ │ ├── StudentMapper.java
│ │ │ │ └── TutorMapper.java
│ │ │ ├── services/
│ │ │ │ ├── CourseService.java
│ │ │ │ ├── StudentService.java
│ │ │ │ └── TutorService.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ ├── AddressMapper.xml
│ │ │ ├── CourseMapper.xml
│ │ │ ├── StudentMapper.xml
│ │ │ └── TutorMapper.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── CourseServiceTest.java
│ ├── StudentServiceTest.java
│ ├── TestDataPopulator.java
│ └── TutorServiceTest.java
├── chapter04/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ ├── Address.java
│ │ │ │ ├── Course.java
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ ├── Student.java
│ │ │ │ └── Tutor.java
│ │ │ ├── mappers/
│ │ │ │ ├── AddressMapper.java
│ │ │ │ ├── StudentMapper.java
│ │ │ │ └── TutorMapper.java
│ │ │ ├── services/
│ │ │ │ ├── StudentService.java
│ │ │ │ └── TutorService.java
│ │ │ ├── sqlproviders/
│ │ │ │ └── TutorDynaSqlProvider.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ ├── StudentMapper.xml
│ │ │ └── TutorMapper.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── StudentServiceTest.java
│ ├── TestDataPopulator.java
│ └── TutorServiceTest.java
├── chapter05/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── config/
│ │ │ │ └── AppConfig.java
│ │ │ ├── domain/
│ │ │ │ ├── Address.java
│ │ │ │ ├── Course.java
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ ├── Student.java
│ │ │ │ └── Tutor.java
│ │ │ ├── mappers/
│ │ │ │ ├── AddressMapper.java
│ │ │ │ ├── StudentMapper.java
│ │ │ │ └── TutorMapper.java
│ │ │ ├── services/
│ │ │ │ ├── StudentService.java
│ │ │ │ └── TutorService.java
│ │ │ ├── sqlproviders/
│ │ │ │ └── TutorDynaSqlProvider.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── applicationContext.xml
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ ├── StudentMapper.xml
│ │ │ └── TutorMapper.xml
│ │ ├── log4j.properties
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── StudentServiceTest.java
│ ├── TestDataPopulator.java
│ └── TutorServiceTest.java
└── elearning/
├── README.txt
├── pom.xml
└── src/
└── main/
├── resources/
│ └── log4j.properties
└── webapp/
├── WEB-INF/
│ └── web.xml
└── index.jsp
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.project
.classpath
.settings
.springBeans
target
bin
build
*.class
# Package Files #
*.jar
*.war
*.ear
================================================
FILE: README.md
================================================
Java Persistence with MyBatis3 Book Sample Code
========================
1. Getting started with MyBatis
2. Bootstrapping MyBatis
3. SQL Mappers using XML
4. SQL Mappers using Annotations
5. Integration with Spring
================================================
FILE: chapter01/README.txt
================================================
Chapter 1: Getting started with MyBatis
=======================================
This module, chapter01, is a maven based java project with MyBatis configured.
How to Run:
1. Create MySQL Database tables using scripts in src/main/resources/sql folder.
2. Configure Database Connection properties like hostname, username and password in src/main/resources/application.properties file.
3. Run StudentServiceTest JUnit Test class.
================================================
FILE: chapter01/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mybatis3</groupId>
<artifactId>chapter01</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>chapter01</name>
<url>http://www.mybatis.org</url>
<description>MyBatis Book Chapter 01</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.11</junit.version>
<slf4j.version>1.7.5</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.2.2</mybatis.version>
<mysql.version>5.1.21</mysql.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
================================================
FILE: chapter01/src/main/java/com/mybatis3/domain/Student.java
================================================
package com.mybatis3.domain;
import java.util.Date;
/**
* @author Siva
*
*/
public class Student
{
private Integer studId;
private String name;
private String email;
private Date dob;
public Student() {
}
public Student(Integer studId) {
this.studId = studId;
}
public Student(Integer studId, String name, String email, Date dob) {
this.studId = studId;
this.name = name;
this.email = email;
this.dob = dob;
}
@Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email="
+ email + ", dob=" + dob + "]";
}
public Integer getStudId() {
return studId;
}
public void setStudId(Integer studId) {
this.studId = studId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
================================================
FILE: chapter01/src/main/java/com/mybatis3/mappers/StudentMapper.java
================================================
package com.mybatis3.mappers;
import java.util.List;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public interface StudentMapper
{
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
void updateStudent(Student student);
}
================================================
FILE: chapter01/src/main/java/com/mybatis3/services/JdbcStudentService.java
================================================
package com.mybatis3.services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public class JdbcStudentService
{
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/elearning";
private static final String USERNAME = "root";
private static final String PASSWORD = "admin";
public static void main(String[] args)
{
JdbcStudentService service = new JdbcStudentService();
Student existingStudent = service.findStudentById(1);
System.out.println(existingStudent);
long ts = System.currentTimeMillis();//For creating unique student names
Student newStudent = new Student(0,"student_"+ts,"student_"+ts+"@gmail.com",new Date());
service.createStudent(newStudent);
System.out.println(newStudent);
int updateStudId = 3;
Student updateStudent = service.findStudentById(updateStudId);
ts = System.currentTimeMillis();//For creating unique student email
updateStudent.setEmail("student_"+ts+"@gmail.com");
service.updateStudent(updateStudent);
}
public Student findStudentById(int studId)
{
Student student = null;
Connection conn = null;
try
{
conn = getDatabaseConnection();
String sql = "select * from students where stud_id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, studId);
ResultSet rs = pstmt.executeQuery();
if(rs.next())
{
student = new Student();
student.setStudId(rs.getInt("stud_id"));
student.setName(rs.getString("name"));
student.setEmail(rs.getString("email"));
student.setDob(rs.getDate("dob"));
}
} catch (SQLException e)
{
throw new RuntimeException(e);
}
finally
{
if(conn!= null){
try {
conn.close();
} catch (SQLException e){ }
}
}
return student;
}
public void createStudent(Student student)
{
Connection conn = null;
try
{
conn = getDatabaseConnection();
String sql = "INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, student.getStudId());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getEmail());
pstmt.setDate(4, new java.sql.Date(student.getDob().getTime()));
pstmt.executeUpdate();
} catch (SQLException e)
{
throw new RuntimeException(e);
}
finally
{
if(conn!= null){
try {
conn.close();
} catch (SQLException e){ }
}
}
}
public void updateStudent(Student student)
{
Connection conn = null;
try
{
conn = getDatabaseConnection();
conn = getDatabaseConnection();
String sql = "UPDATE STUDENTS SET NAME=?,EMAIL=?,DOB=? WHERE STUD_ID=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getEmail());
pstmt.setDate(3, new java.sql.Date(student.getDob().getTime()));
pstmt.setInt(4, student.getStudId());
pstmt.executeUpdate();
} catch (SQLException e)
{
throw new RuntimeException(e.getCause());
}
finally
{
if(conn!= null){
try {
conn.close();
} catch (SQLException e){ }
}
}
}
protected Connection getDatabaseConnection() throws SQLException
{
try
{
Class.forName(JdbcStudentService.DRIVER);
return DriverManager.getConnection(JdbcStudentService.URL,
JdbcStudentService.USERNAME,
JdbcStudentService.PASSWORD);
} catch (SQLException e)
{
throw e;
} catch (Exception e)
{
throw new RuntimeException(e.getCause());
}
}
}
================================================
FILE: chapter01/src/main/java/com/mybatis3/services/StudentService.java
================================================
package com.mybatis3.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.util.MyBatisSqlSessionFactory;
/**
* @author Siva
*
*/
public class StudentService
{
private Logger logger = LoggerFactory.getLogger(getClass());
public List<Student> findAllStudents()
{
SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
} finally {
sqlSession.close();
}
}
public Student findStudentById(Integer studId)
{
logger.debug("Select Student By ID :{}", studId);
SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
//return sqlSession.selectOne("com.mybatis3.StudentMapper.findStudentById", studId);
} finally {
sqlSession.close();
}
}
public void createStudent(Student student)
{
SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
public void updateStudent(Student student)
{
SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.updateStudent(student);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter01/src/main/java/com/mybatis3/util/MyBatisSqlSessionFactory.java
================================================
package com.mybatis3.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @author Siva
*
*/
public class MyBatisSqlSessionFactory
{
private static SqlSessionFactory sqlSessionFactory;
private static final Properties PROPERTIES = new Properties();
static
{
try {
InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory()
{
if(sqlSessionFactory==null)
{
InputStream inputStream = null;
try
{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e)
{
throw new RuntimeException(e.getCause());
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
return sqlSessionFactory;
}
public static SqlSession getSqlSession()
{
return getSqlSessionFactory().openSession();
}
public static Connection getConnection()
{
String driver = PROPERTIES.getProperty("jdbc.driverClassName");
String url = PROPERTIES.getProperty("jdbc.url");
String username = PROPERTIES.getProperty("jdbc.username");
String password = PROPERTIES.getProperty("jdbc.password");
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return connection;
}
}
================================================
FILE: chapter01/src/main/resources/application.properties
================================================
################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/elearning
jdbc.username=root
jdbc.password=admin
================================================
FILE: chapter01/src/main/resources/com/mybatis3/mappers/StudentMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
select * from Students
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
select stud_id as studId, name, email, dob from Students where stud_id=#{studId}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
</insert>
<update id="updateStudent" parameterType="Student">
UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
</update>
</mapper>
================================================
FILE: chapter01/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
================================================
FILE: chapter01/src/main/resources/mybatis-config.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="application.properties"/>
<typeAliases>
<package name="com.mybatis3.domain"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
</mappers>
</configuration>
================================================
FILE: chapter01/src/main/resources/sql/create_tables.sql
================================================
CREATE TABLE ADDRESSES
(
ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
STREET VARCHAR(50) NOT NULL,
CITY VARCHAR(50) NOT NULL,
STATE VARCHAR(50) NOT NULL,
ZIP VARCHAR(10) DEFAULT NULL,
COUNTRY VARCHAR(50) NOT NULL,
PRIMARY KEY (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE STUDENTS
(
STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (STUD_ID),
CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE TUTORS
(
TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (TUTOR_ID),
CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSES
(
COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
DESCRIPTION VARCHAR(512) DEFAULT NULL,
START_DATE DATE DEFAULT NULL,
END_DATE DATE DEFAULT NULL,
TUTOR_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID),
CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSE_ENROLLMENT
(
COURSE_ID INT(11) NOT NULL,
STUD_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID,STUD_ID),
CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
CREATE TABLE USER_PICS
(
ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) DEFAULT NULL,
PIC BLOB,
BIO LONGTEXT,
PRIMARY KEY (ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
================================================
FILE: chapter01/src/main/resources/sql/drop_tables.sql
================================================
DROP TABLE IF EXISTS USER_PICS;
DROP TABLE IF EXISTS COURSE_ENROLLMENT;
DROP TABLE IF EXISTS COURSES;
DROP TABLE IF EXISTS TUTORS;
DROP TABLE IF EXISTS STUDENTS;
DROP TABLE IF EXISTS ADDRESSES;
================================================
FILE: chapter01/src/main/resources/sql/sample_data.sql
================================================
--Sample data for table ADDRESSES
INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
(1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
(2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
(3,'710 N Cable Rd','Lima','OH','45825','Allen'),
(4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
-- Sample data for table STUDENTS
INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
(1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
(2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
-- Sample data for table TUTORS
INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
(1,'John','john@gmail.com','111-222-3333','1980-05-20',NULL,NULL,1),
(2,'Paul','paul@gmail.com','123-321-4444','1981-03-15',NULL,NULL,2);
-- Sample data for table courses
INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
(1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
(2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
(3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
-- Sample data for table COURSE_ENROLLMENT
INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
(1,1),
(1,2),
(2,2);
================================================
FILE: chapter01/src/test/java/com/mybatis3/services/StudentServiceTest.java
================================================
package com.mybatis3.services;
import java.util.Date;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public class StudentServiceTest
{
private static StudentService studentService;
@BeforeClass
public static void setup()
{
studentService = new StudentService();
TestDataPopulator.initDatabase();
}
@AfterClass
public static void teardown()
{
studentService = null;
}
@Test
public void testFindAllStudents()
{
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
assertNotNull(student);
//System.out.println(student);
}
}
@Test
public void testFindStudentById()
{
Student student = studentService.findStudentById(1);
assertNotNull(student);
}
@Test
public void testCreateUStudent()
{
Student student = new Student();
int id = 4;
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
student.setDob(new Date());
studentService.createStudent(student);
Student newStudent = studentService.findStudentById(id);
assertNotNull(newStudent);
assertEquals("student_"+id, newStudent.getName());
assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
}
@Test
public void testUpdateStudent()
{
int id = 2;
Student student =studentService.findStudentById(id);
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
Date now = new Date();
student.setDob(now);
studentService.updateStudent(student);
Student updatedStudent = studentService.findStudentById(id);
assertNotNull(updatedStudent);
assertEquals("student_"+id, updatedStudent.getName());
assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());
}
}
================================================
FILE: chapter01/src/test/java/com/mybatis3/services/TestDataPopulator.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.util.MyBatisSqlSessionFactory;
/**
* @author Siva
*
*/
public class TestDataPopulator
{
private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
public static void main(String[] args) {
initDatabase();
}
public static void initDatabase()
{
Connection connection = null;
Reader reader = null;
try {
connection = MyBatisSqlSessionFactory.getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
reader = Resources.getResourceAsReader("sql/drop_tables.sql");
scriptRunner.runScript(reader);
logger.info("drop_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/create_tables.sql");
scriptRunner.runScript(reader );
logger.info("create_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/sample_data.sql");
scriptRunner.runScript(reader );
logger.info("sample_data.sql executed successfully");
connection.commit();
reader.close();
scriptRunner.closeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
================================================
FILE: chapter01/src/test/resources/log4j.properties
================================================
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
================================================
FILE: chapter02/README.txt
================================================
Chapter 2: Bootstrapping MyBatis
=======================================
This module, chapter02, is a maven based java project to demonstrate the following approaches to configure and bootstrap MyBatis.
. Configuration using XML
. Configuration using Java API.
Note: You can create MySQL Database tables using scripts in src/main/resources/sql folder.
How to Run:
1. Configure Database Connection properties like hostname, username and password in src/main/resources/application.properties file.
2. Run StudentServiceTest JUnit Test class by using the appropriate configuration style in com.mybatis3.services.StudentServiceTest.setup() method.
================================================
FILE: chapter02/pom.xml
================================================
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mybatis3</groupId>
<artifactId>chapter02</artifactId>
<version>0.0.1</version>
<name>chapter02</name>
<url>http://www.mybatis.org</url>
<description>MyBatis Book Chapter 02</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.11</junit.version>
<slf4j.version>1.7.5</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.2.2</mybatis.version>
<mysql.version>5.1.21</mysql.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
================================================
FILE: chapter02/src/main/java/com/mybatis3/domain/PhoneNumber.java
================================================
/**
*
*/
package com.mybatis3.domain;
/**
* @author Siva
*
*/
public class PhoneNumber
{
private String countryCode;
private String stateCode;
private String number;
public PhoneNumber() {
}
public PhoneNumber(String countryCode, String stateCode, String number) {
super();
this.countryCode = countryCode;
this.stateCode = stateCode;
this.number = number;
}
public PhoneNumber(String string) {
if(string != null){
String[] parts = string.split("-");
if(parts.length>0) this.countryCode=parts[0];
if(parts.length>1) this.stateCode=parts[1];
if(parts.length>2) this.number=parts[2];
}
}
@Override
public String toString() {
return this.getAsString();
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAsString() {
return countryCode+"-"+stateCode+"-"+number;
}
}
================================================
FILE: chapter02/src/main/java/com/mybatis3/domain/Student.java
================================================
package com.mybatis3.domain;
import java.util.Date;
import org.apache.ibatis.type.Alias;
/**
* @author Siva
*
*/
@Alias("Student")
public class Student
{
private Integer studId;
private String name;
private String email;
private Date dob;
public Student() {
}
public Student(Integer studId) {
this.studId = studId;
}
public Student(Integer studId, String name, String email, Date dob) {
this.studId = studId;
this.name = name;
this.email = email;
this.dob = dob;
}
@Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email="
+ email + ", dob=" + dob + "]";
}
public Integer getStudId() {
return studId;
}
public void setStudId(Integer studId) {
this.studId = studId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
================================================
FILE: chapter02/src/main/java/com/mybatis3/mappers/StudentMapper.java
================================================
package com.mybatis3.mappers;
import java.util.List;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public interface StudentMapper
{
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
void updateStudent(Student student);
}
================================================
FILE: chapter02/src/main/java/com/mybatis3/services/StudentService.java
================================================
package com.mybatis3.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
public class StudentService
{
private Logger logger = LoggerFactory.getLogger(getClass());
private SqlSessionFactory factory;
public StudentService(SqlSessionFactory factory) {
this.factory = factory;
}
protected SqlSession openSqlSession()
{
return factory.openSession();
}
public List<Student> findAllStudents()
{
SqlSession sqlSession = openSqlSession();
try {
//sqlSession.selectList("com.mybatis3.mappers.StudentMapper.findAllStudents");
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
} finally {
sqlSession.close();
}
}
public Student findStudentById(Integer studId)
{
logger.debug("Select Student By ID :{}", studId);
SqlSession sqlSession = openSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
} finally {
sqlSession.close();
}
}
public Student createStudent(Student student)
{
SqlSession sqlSession = openSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
return student;
} finally {
sqlSession.close();
}
}
public void updateStudent(Student student)
{
SqlSession sqlSession = openSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.updateStudent(student);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter02/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
================================================
/**
*
*/
package com.mybatis3.typehandlers;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.mybatis3.domain.PhoneNumber;
/**
* @author Siva
*
*/
public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.getAsString());
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return new PhoneNumber(rs.getString(columnName));
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return new PhoneNumber(rs.getString(columnIndex));
}
@Override
public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return new PhoneNumber(cs.getString(columnIndex));
}
}
================================================
FILE: chapter02/src/main/java/com/mybatis3/util/DataSourceFactory.java
================================================
/**
*
*/
package com.mybatis3.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
/**
* @author Siva
*
*/
public class DataSourceFactory
{
private static final Properties PROPERTIES = new Properties();
static
{
try {
InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static DataSource getDataSource()
{
String driver = PROPERTIES.getProperty("jdbc.driverClassName");
String url = PROPERTIES.getProperty("jdbc.url");
String username = PROPERTIES.getProperty("jdbc.username");
String password = PROPERTIES.getProperty("jdbc.password");
PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);
return dataSource;
}
public static DataSource getJNDIDataSource()
{
String dataSourceJNDIName = "java:comp/env/jdbc/MyBatisDemoDS";
try
{
InitialContext ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(dataSourceJNDIName);
return dataSource;
}
catch (NamingException e)
{
throw new RuntimeException(e);
}
}
}
================================================
FILE: chapter02/src/main/java/com/mybatis3/util/MyBatisUtil.java
================================================
package com.mybatis3.util;
import java.io.IOException;
import java.io.InputStream;
import javax.sql.DataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.typehandlers.PhoneTypeHandler;
/**
* @author Siva
*
*/
public class MyBatisUtil
{
private static SqlSessionFactory xmlSqlSessionFactory;
private static SqlSessionFactory javaSqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactoryUsingXML()
{
if(xmlSqlSessionFactory==null)
{
InputStream inputStream;
try
{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
xmlSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e)
{
throw new RuntimeException(e);
}
}
return xmlSqlSessionFactory;
}
public static SqlSessionFactory getSqlSessionFactoryUsingJavaAPI()
{
if(javaSqlSessionFactory==null)
{
try
{
DataSource dataSource = DataSourceFactory.getDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.getTypeAliasRegistry().registerAlias("student", Student.class);
configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.class);
configuration.addMapper(StudentMapper.class);
javaSqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
return javaSqlSessionFactory;
}
}
================================================
FILE: chapter02/src/main/resources/application.properties
================================================
################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/elearning
jdbc.username=root
jdbc.password=admin
================================================
FILE: chapter02/src/main/resources/com/mybatis3/mappers/StudentMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
select * from Students
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
select stud_id as studId, name, email, dob from Students where stud_id=#{studId}
</select>
<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
INSERT INTO STUDENTS(NAME,EMAIL,DOB) VALUES(#{name},#{email},#{dob})
</insert>
<update id="updateStudent" parameterType="Student">
UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
</update>
</mapper>
================================================
FILE: chapter02/src/main/resources/full-mybatis-config.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- This file is for a reference purpose for various configuration options -->
<properties resource="application.properties">
<property name="username" value="db_user"/>
<property name="password" value="verysecurepwd"/>
</properties>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<typeAliases>
<typeAlias alias="Tutor" type="com.mybatis3.domain.Tutor"/>
<package name="com.mybatis3.domain"/>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/>
<package name="com.mybatis3.typehandlers"/>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
<environment id="production">
<transactionManager type="JDBC"/>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/jdbc/MyBatisDemoDS"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
<mapper url="file:///var/mappers/StudentMapper.xml"/>
<mapper class="com.mybatis3.mappers.TutorMapper"/>
</mappers>
</configuration>
================================================
FILE: chapter02/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
================================================
FILE: chapter02/src/main/resources/mybatis-config.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="application.properties">
<property name="jdbc.username" value="root"/>
<property name="jdbc.password" value="verysecurepwd"/>
</properties>
<!-- <settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings> -->
<typeAliases>
<package name="com.mybatis3.domain"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
<!-- <package name="com.mybatis3.mappers"/> -->
</mappers>
</configuration>
================================================
FILE: chapter02/src/main/resources/sql/create_tables.sql
================================================
CREATE TABLE ADDRESSES
(
ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
STREET VARCHAR(50) NOT NULL,
CITY VARCHAR(50) NOT NULL,
STATE VARCHAR(50) NOT NULL,
ZIP VARCHAR(10) DEFAULT NULL,
COUNTRY VARCHAR(50) NOT NULL,
PRIMARY KEY (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE STUDENTS
(
STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (STUD_ID),
CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE TUTORS
(
TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (TUTOR_ID),
CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSES
(
COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
DESCRIPTION VARCHAR(512) DEFAULT NULL,
START_DATE DATE DEFAULT NULL,
END_DATE DATE DEFAULT NULL,
TUTOR_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID),
CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSE_ENROLLMENT
(
COURSE_ID INT(11) NOT NULL,
STUD_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID,STUD_ID),
CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
CREATE TABLE USER_PICS
(
ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) DEFAULT NULL,
PIC BLOB,
BIO LONGTEXT,
PRIMARY KEY (ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
================================================
FILE: chapter02/src/main/resources/sql/drop_tables.sql
================================================
DROP TABLE IF EXISTS USER_PICS;
DROP TABLE IF EXISTS COURSE_ENROLLMENT;
DROP TABLE IF EXISTS COURSES;
DROP TABLE IF EXISTS TUTORS;
DROP TABLE IF EXISTS STUDENTS;
DROP TABLE IF EXISTS ADDRESSES;
================================================
FILE: chapter02/src/main/resources/sql/sample_data.sql
================================================
--Sample data for table ADDRESSES
INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
(1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
(2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
(3,'710 N Cable Rd','Lima','OH','45825','Allen'),
(4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
-- Sample data for table STUDENTS
INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
(1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
(2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
-- Sample data for table TUTORS
INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
(1,'John','john@gmail.com','111-222-3333','1980-05-20',NULL,NULL,1),
(2,'Paul','paul@gmail.com','123-321-4444','1981-03-15',NULL,NULL,2);
-- Sample data for table courses
INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
(1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
(2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
(3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
-- Sample data for table COURSE_ENROLLMENT
INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
(1,1),
(1,2),
(2,2);
================================================
FILE: chapter02/src/test/java/com/mybatis3/services/StudentServiceTest.java
================================================
package com.mybatis3.services;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.Student;
import com.mybatis3.util.MyBatisUtil;
public class StudentServiceTest
{
private static StudentService studentService;
@BeforeClass
public static void setup()
{
TestDataPopulator.initDatabase();
SqlSessionFactory sqlSessionFactory = null;
//Use this if you want XML based configuration
sqlSessionFactory = MyBatisUtil.getSqlSessionFactoryUsingXML();
//Use this if you want to use Java API configuration
//sqlSessionFactory = MyBatisUtil.getSqlSessionFactoryUsingJavaAPI();
studentService = new StudentService(sqlSessionFactory);
}
@AfterClass
public static void teardown()
{
studentService = null;
}
@Test
public void testFindAllStudents()
{
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
assertNotNull(student);
//System.out.println(student);
}
}
@Test
public void testFindStudentById()
{
Student student = studentService.findStudentById(1);
assertNotNull(student);
}
@Test
public void testCreateUStudent()
{
Student student = new Student();
int id = 4;
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
student.setDob(new Date());
Student newStudent = studentService.createStudent(student);
assertNotNull(newStudent);
assertEquals("student_"+id, newStudent.getName());
assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
}
@Test
public void testUpdateStudent()
{
int id = 2;
Student student =studentService.findStudentById(id);
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
Date now = new Date();
student.setDob(now);
studentService.updateStudent(student);
Student updatedStudent = studentService.findStudentById(id);
assertNotNull(updatedStudent);
assertEquals("student_"+id, updatedStudent.getName());
assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());
}
}
================================================
FILE: chapter02/src/test/java/com/mybatis3/services/TestDataPopulator.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.util.DataSourceFactory;
/**
* @author Siva
*
*/
public class TestDataPopulator
{
private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
public static void main(String[] args) {
initDatabase();
}
public static void initDatabase()
{
Connection connection = null;
Reader reader = null;
try {
connection = DataSourceFactory.getDataSource().getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
reader = Resources.getResourceAsReader("sql/drop_tables.sql");
scriptRunner.runScript(reader);
logger.info("drop_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/create_tables.sql");
scriptRunner.runScript(reader );
logger.info("create_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/sample_data.sql");
scriptRunner.runScript(reader );
logger.info("sample_data.sql executed successfully");
connection.commit();
reader.close();
scriptRunner.closeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
================================================
FILE: chapter03/README.txt
================================================
Chapter 3: SQL Mappers using XML
=================================
This chapter describes mapping SQL statements and query results to java beans in SQL Mappers using XML based approach.
Topics covered:
• CRUD Mapping
• ResultSet Mapping
• One-To-One, One-To-Many mappings
• Dynamic SQL mapping
How to Run:
1. Configure Database Connection properties like hostname, username and password in src/main/resources/application.properties file.
2. Run JUnit Test classes in com.mybatis3.services package under src/test/java/ folder.
================================================
FILE: chapter03/pom.xml
================================================
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mybatis3</groupId>
<artifactId>chapter03</artifactId>
<version>0.0.1</version>
<name>chapter03</name>
<url>http://www.mybatis.org</url>
<description>MyBatis Book Chapter 03</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.11</junit.version>
<slf4j.version>1.7.5</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.2.2</mybatis.version>
<mysql.version>5.1.21</mysql.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
================================================
FILE: chapter03/src/main/java/com/mybatis3/domain/Address.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class Address implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer addrId;
private String street;
private String city;
private String state;
private String zip;
private String country;
@Override
public String toString() {
return "Address [addrId=" + addrId + ", street=" + street + ", city=" + city
+ ", state=" + state + ", zip=" + zip + ", country=" + country
+ "]";
}
public Address()
{
}
public Address(Integer addrId)
{
this.addrId = addrId;
}
public Address(Integer addrId, String street, String city, String state,
String zip, String country)
{
this.addrId = addrId;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
}
public Integer getAddrId() {
return addrId;
}
public void setAddrId(Integer addrId) {
this.addrId = addrId;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getZip()
{
return zip;
}
public void setZip(String zip)
{
this.zip = zip;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/domain/Course.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Siva
*
*/
public class Course implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer courseId;
private String name;
private String description;
private Date startDate;
private Date endDate;
private Tutor tutor;
private List<Student> students;
@Override
public String toString() {
return "Course [courseId=" + courseId + ", name=" + name + ", description="
+ description + ", startDate=" + startDate + ", endDate="
+ endDate + ", tutor=" + tutor + ", students=" + students + "]";
}
public Integer getCourseId()
{
return courseId;
}
public void setCourseId(Integer id)
{
this.courseId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Date getStartDate()
{
return startDate;
}
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
public Date getEndDate()
{
return endDate;
}
public void setEndDate(Date endDate)
{
this.endDate = endDate;
}
public List<Student> getStudents()
{
if(students == null){
students = new ArrayList<Student>(0);
}
return students;
}
public void setStudents(List<Student> students)
{
this.students = students;
}
public Tutor getTutor() {
return tutor;
}
public void setTutor(Tutor tutor) {
this.tutor = tutor;
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/domain/PhoneNumber.java
================================================
/**
*
*/
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class PhoneNumber implements Serializable
{
private static final long serialVersionUID = 1L;
private String countryCode;
private String stateCode;
private String number;
public PhoneNumber() {
}
public PhoneNumber(String countryCode, String stateCode, String number) {
super();
this.countryCode = countryCode;
this.stateCode = stateCode;
this.number = number;
}
public PhoneNumber(String string) {
if(string != null){
String[] parts = string.split("-");
if(parts.length>0) this.countryCode=parts[0];
if(parts.length>1) this.stateCode=parts[1];
if(parts.length>2) this.number=parts[2];
}
}
/*@Override
public String toString() {
return this.getAsString();
}*/
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAsString() {
return countryCode+"-"+stateCode+"-"+number;
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/domain/Student.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class Student implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer studId;
private String name;
private String email;
private PhoneNumber phone;
private Address address;
@Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email=" + email
+ ", phone=" + (phone==null?null:phone.getAsString()) + ", address=" + address + "]";
}
public Student()
{
}
public Student(Integer id)
{
this.studId = id;
}
public Integer getStudId()
{
return studId;
}
public void setStudId(Integer id)
{
this.studId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/domain/Tutor.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
import java.util.List;
/**
* @author Siva
*
*/
public class Tutor implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer tutorId;
private String name;
private String email;
private Address address;
private List<Course> courses;
@Override
public String toString() {
return "Tutor [tutorId=" + tutorId + ", name=" + name + ", email=" + email
+ ", address=" + address + ", courses=" + courses + "]";
}
public Tutor()
{
}
public Tutor(Integer id)
{
this.tutorId = id;
}
public Integer getTutorId()
{
return tutorId;
}
public void setTutorId(Integer id)
{
this.tutorId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Address getAddress()
{
return address;
}
public void setAddress(Address address)
{
this.address = address;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/mappers/AddressMapper.java
================================================
package com.mybatis3.mappers;
import com.mybatis3.domain.Address;
/**
* @author Siva
*
*/
public interface AddressMapper
{
Address findAddressById(Integer id);
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/mappers/CourseMapper.java
================================================
package com.mybatis3.mappers;
import java.util.List;
import java.util.Map;
import com.mybatis3.domain.Course;
/**
* @author Siva
*
*/
public interface CourseMapper
{
List<Course> selectCoursesByTutor(int tutorId);
List<Course> searchCourses(Map<String, Object> map);
List<Course> searchCoursesByTutors(Map<String, Object> map);
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/mappers/StudentMapper.java
================================================
package com.mybatis3.mappers;
import java.util.List;
import java.util.Map;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public interface StudentMapper
{
List<Student> findAllStudents();
Student findStudentById(Integer id);
Student selectStudentWithAddress(int id);
void insertStudent(Student student);
void insertStudentWithMap(Map<String, Object> map);
void updateStudent(Student student);
int deleteStudent(int id);
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/mappers/TutorMapper.java
================================================
package com.mybatis3.mappers;
import com.mybatis3.domain.Tutor;
/**
* @author Siva
*
*/
public interface TutorMapper
{
Tutor selectTutorWithCourses(int tutorId);
Tutor selectTutorById(int tutorId);
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/services/CourseService.java
================================================
package com.mybatis3.services;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.domain.Course;
import com.mybatis3.mappers.CourseMapper;
import com.mybatis3.util.MyBatisUtil;
public class CourseService
{
private Logger logger = LoggerFactory.getLogger(getClass());
public List<Course> searchCourses(Map<String, Object> map)
{
logger.debug("searchCourses By :"+map);
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
return mapper.searchCourses(map);
}
finally {
sqlSession.close();
}
}
public List<Course> searchCoursesByTutors(Map<String, Object> map) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
return mapper.searchCoursesByTutors(map);
}
finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/services/StudentService.java
================================================
package com.mybatis3.services;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.util.MyBatisUtil;
public class StudentService
{
public List<Student> findAllStudents()
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
} finally {
sqlSession.close();
}
}
public Student findStudentById(Integer id)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(id);
} finally {
sqlSession.close();
}
}
public Student findStudentWithAddressById(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.selectStudentWithAddress(id);
} finally {
sqlSession.close();
}
}
public Student createStudent(Student student) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.insertStudent(student);
sqlSession.commit();
return student;
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public void createStudentWithMap(Map<String, Object> studentDataMap) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.insertStudentWithMap(studentDataMap);
sqlSession.commit();
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public Student updateStudent(Student student) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.updateStudent(student);
sqlSession.commit();
return student;
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public boolean deleteStudent(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int count = mapper.deleteStudent(id);
sqlSession.commit();
return count > 0;
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/services/TutorService.java
================================================
package com.mybatis3.services;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.domain.Tutor;
import com.mybatis3.mappers.TutorMapper;
import com.mybatis3.util.MyBatisUtil;
public class TutorService
{
private Logger logger = LoggerFactory.getLogger(getClass());
public Tutor findTutorById(int tutorId) {
logger.debug("findTutorById :"+tutorId);
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
return mapper.selectTutorById(tutorId);
}
finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
================================================
/**
*
*/
package com.mybatis3.typehandlers;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.mybatis3.domain.PhoneNumber;
/**
* @author Siva
*
*/
public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.getAsString());
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return new PhoneNumber(rs.getString(columnName));
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return new PhoneNumber(rs.getString(columnIndex));
}
@Override
public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return new PhoneNumber(cs.getString(columnIndex));
}
}
================================================
FILE: chapter03/src/main/java/com/mybatis3/util/MyBatisUtil.java
================================================
package com.mybatis3.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @author Siva
*
*/
public class MyBatisUtil
{
private static final String DEFAULT_MYBATIS_CONFIG_FILE="mybatis-config.xml";
private static SqlSessionFactory sqlSessionFactory;
private static final Properties PROPERTIES = new Properties();
static
{
try {
InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory()
{
if(sqlSessionFactory==null){
//org.apache.ibatis.logging.LogFactory.useLog4JLogging();
try
{
InputStream inputStream = Resources.getResourceAsStream(DEFAULT_MYBATIS_CONFIG_FILE);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e)
{
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
public static Connection getConnection()
{
String driver = PROPERTIES.getProperty("jdbc.driverClassName");
String url = PROPERTIES.getProperty("jdbc.url");
String username = PROPERTIES.getProperty("jdbc.username");
String password = PROPERTIES.getProperty("jdbc.password");
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return connection;
}
}
================================================
FILE: chapter03/src/main/resources/application.properties
================================================
################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/elearning
jdbc.username=root
jdbc.password=admin
================================================
FILE: chapter03/src/main/resources/com/mybatis3/mappers/AddressMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.AddressMapper">
<resultMap type="Address" id="AddressResult">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</resultMap>
<select id="selectAddressById" parameterType="int" resultMap="AddressResult">
select * from addresses where addr_id=#{addrId}
</select>
</mapper>
================================================
FILE: chapter03/src/main/resources/com/mybatis3/mappers/CourseMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.CourseMapper">
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="false"/>
<resultMap type="Course" id="CourseResult">
<id column="course_id" property="courseId"/>
<result column="name" property="name"/>
<result column="description" property="description"/>
<result column="start_date" property="startDate"/>
<result column="end_date" property="endDate"/>
</resultMap>
<select id="selectCoursesByTutor" parameterType="int" resultMap="CourseResult">
select * from courses where tutor_id=#{tutorId}
</select>
<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult" useCache="false">
SELECT * FROM COURSES
WHERE TUTOR_ID= #{tutorId}
<if test="courseName != null">
AND name like #{courseName}
</if>
<if test="startDate != null">
AND start_date >= #{startDate}
</if>
<if test="endDate != null">
AND end_date <= #{endDate}
</if>
</select>
<select id="searchCoursesByTutors" parameterType="hashmap" resultMap="CourseResult">
SELECT * FROM COURSES
<if test="tutorIds != null">
<where>
tutor_id IN
<foreach item="tutorId" collection="tutorIds"
open="(" separator="," close=")">
#{tutorId}
</foreach>
</where>
</if>
</select>
</mapper>
================================================
FILE: chapter03/src/main/resources/com/mybatis3/mappers/StudentMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name" />
<result property="email" column="email"/>
<result property="phone" column="phone"/>
</resultMap>
<resultMap type="Student" id="StudentWithAddressExtResult" extends="StudentResult">
<result property="address.addrId" column="addr_id"/>
<result property="address.street" column="street"/>
<result property="address.city" column="city"/>
<result property="address.state" column="state"/>
<result property="address.zip" column="zip"/>
<result property="address.country" column="country"/>
</resultMap>
<resultMap type="Student" id="StudentWithAddressNestedSelect">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<association property="address" column="addr_id" select="com.mybatis3.mappers.AddressMapper.selectAddressById"/>
</resultMap>
<resultMap type="Student" id="StudentWithAddressNestedResultMap">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<association property="address" javaType="Address">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</association>
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
select * from Students
</select>
<select id="findStudentById" parameterType="int" resultMap="StudentWithAddressNestedSelect">
select * from Students where stud_id=#{studId}
</select>
<select id="selectStudentWithAddress" parameterType="int" resultMap="StudentWithAddressNestedResultMap">
select stud_id, name, email,phone, a.addr_id, street, city, state, zip, country
FROM students s left outer join addresses a on s.addr_id=a.addr_id
where stud_id=#{studId}
</select>
<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
insert into students(name,email,addr_id, phone)
values(#{name},#{email},#{address.addrId},#{phone})
</insert>
<insert id="insertStudentWithMap" parameterType="hashmap" useGeneratedKeys="true" keyProperty="studId">
insert into students(name,email,addr_id,phone)
values(#{name},#{email},#{address.addrId},#{phone})
</insert>
<update id="updateStudent" parameterType="Student">
update students
<!-- set
name=#{name},
email=#{email},
phone=#{phone}
where stud_id=#{studId} -->
<set>
<if test="name != null">name=#{name},</if>
<if test="email != null">email=#{email},</if>
<if test="phone != null">phone=#{phone},</if>
</set>
where stud_id=#{studId}
</update>
<delete id="deleteStudent" parameterType="int">
delete from students where stud_id=#{studId}
</delete>
</mapper>
================================================
FILE: chapter03/src/main/resources/com/mybatis3/mappers/TutorMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.TutorMapper">
<resultMap type="Tutor" id="TutorWithCoursesNestedResult">
<id column="tutor_id" property="tutorId"/>
<result column="tutor_name" property="name"/>
<result column="email" property="email"/>
<association property="address" resultMap="com.mybatis3.mappers.AddressMapper.AddressResult"/>
<collection property="courses" resultMap="com.mybatis3.mappers.CourseMapper.CourseResult" />
</resultMap>
<resultMap type="Tutor" id="TutorWithCoursesNestedSelect">
<id column="tutor_id" property="tutorId"/>
<result column="tutor_name" property="name"/>
<result column="email" property="email"/>
<association property="address" resultMap="com.mybatis3.mappers.AddressMapper.AddressResult"/>
<collection property="courses" column="tutor_id" select="com.mybatis3.mappers.CourseMapper.selectCoursesByTutor"/>
</resultMap>
<select id="selectTutorById" parameterType="int" resultMap="TutorWithCoursesNestedResult">
SELECT t.tutor_id, t.name as tutor_name, email, a.addr_id, street, city, state, zip, country,
course_id, c.name, description, start_date, end_date
FROM tutors t left outer join addresses a on t.addr_id=a.addr_id
left outer join courses c on t.tutor_id=c.tutor_id
where t.tutor_id=#{tutorId}
</select>
<select id="selectTutorWithCourses" parameterType="int" resultMap="TutorWithCoursesNestedSelect">
SELECT t.tutor_id, t.name as tutor_name, email, a.addr_id, street, city, state, zip, country
FROM tutors t left outer join addresses a on t.addr_id=a.addr_id
where t.tutor_id=#{tutorId}
</select>
</mapper>
================================================
FILE: chapter03/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
================================================
FILE: chapter03/src/main/resources/mybatis-config.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="application.properties" />
<typeAliases>
<package name="com.mybatis3.domain" />
</typeAliases>
<typeHandlers>
<typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler" />
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.mybatis3.mappers"/>
</mappers>
</configuration>
================================================
FILE: chapter03/src/main/resources/sql/create_tables.sql
================================================
CREATE TABLE ADDRESSES
(
ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
STREET VARCHAR(50) NOT NULL,
CITY VARCHAR(50) NOT NULL,
STATE VARCHAR(50) NOT NULL,
ZIP VARCHAR(10) DEFAULT NULL,
COUNTRY VARCHAR(50) NOT NULL,
PRIMARY KEY (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE STUDENTS
(
STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
GENDER VARCHAR(6) DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (STUD_ID),
UNIQUE KEY UK_EMAIL (EMAIL),
CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE TUTORS
(
TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
GENDER VARCHAR(6) DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (TUTOR_ID),
UNIQUE KEY UK_EMAIL (EMAIL),
CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSES
(
COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
DESCRIPTION VARCHAR(512) DEFAULT NULL,
START_DATE DATE DEFAULT NULL,
END_DATE DATE DEFAULT NULL,
TUTOR_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID),
CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSE_ENROLLMENT
(
COURSE_ID INT(11) NOT NULL,
STUD_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID,STUD_ID),
CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
================================================
FILE: chapter03/src/main/resources/sql/drop_tables.sql
================================================
DROP TABLE IF EXISTS USER_PICS;
DROP TABLE IF EXISTS COURSE_ENROLLMENT;
DROP TABLE IF EXISTS COURSES;
DROP TABLE IF EXISTS TUTORS;
DROP TABLE IF EXISTS STUDENTS;
DROP TABLE IF EXISTS ADDRESSES;
================================================
FILE: chapter03/src/main/resources/sql/sample_data.sql
================================================
--Sample data for table ADDRESSES
INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
(1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
(2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
(3,'710 N Cable Rd','Lima','OH','45825','Allen'),
(4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
-- Sample data for table STUDENTS
INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
(1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
(2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
-- Sample data for table TUTORS
INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,GENDER,BIO,PIC,ADDR_ID) VALUES
(1,'John','john@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
(2,'Ken','ken@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
(3,'Paul','paul@gmail.com','123-321-4444','1981-03-15','FEMALE',NULL,NULL,2),
(4,'Mike','mike@gmail.com','123-321-4444','1981-03-15','MALE',NULL,NULL,2);
-- Sample data for table courses
INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
(1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
(2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
(3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
-- Sample data for table COURSE_ENROLLMENT
INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
(1,1),
(1,2),
(2,2);
================================================
FILE: chapter03/src/test/java/com/mybatis3/services/CourseServiceTest.java
================================================
package com.mybatis3.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.Course;
public class CourseServiceTest
{
private static CourseService courseService;
@BeforeClass
public static void setup()
{
TestDataPopulator.initDatabase();
courseService = new CourseService();
}
@AfterClass
public static void teardown()
{
courseService = null;
}
@Test
public void searchCourses()
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("tutorId", 1);
//map.put("courseName", "%java%");
map.put("startDate", new Date());
List<Course> courses = courseService.searchCourses(map);
Assert.assertNotNull(courses);
for (Course course : courses) {
Assert.assertNotNull(course);
//System.out.println(course);
}
}
@Test
public void searchCoursesByTutors()
{
Map<String, Object> map = new HashMap<String, Object>();
List<Integer> tutorIds = new ArrayList<Integer>();
tutorIds.add(1);
tutorIds.add(2);
map.put("tutorIds", tutorIds);
map.put("courseName", "%java%");
map.put("startDate", new Date());
List<Course> courses = courseService.searchCoursesByTutors(map);
Assert.assertNotNull(courses);
for (Course course : courses) {
Assert.assertNotNull(course);
//System.out.println(course);
}
}
}
================================================
FILE: chapter03/src/test/java/com/mybatis3/services/StudentServiceTest.java
================================================
package com.mybatis3.services;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.PhoneNumber;
import com.mybatis3.domain.Student;
public class StudentServiceTest
{
private static StudentService studentService;
@BeforeClass
public static void setup()
{
studentService = new StudentService();
TestDataPopulator.initDatabase();
}
@AfterClass
public static void teardown()
{
studentService = null;
}
@Test
public void testFindAllStudents()
{
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
assertNotNull(student);
//System.out.println(student);
}
}
@Test
public void testFindStudentById()
{
Student student = studentService.findStudentById(1);
assertNotNull(student);
System.out.println(student);
}
@Test
public void testFindStudentWithAddressById()
{
Student student = studentService.findStudentWithAddressById(1);
assertNotNull(student);
System.out.println(student);
}
@Test
public void testCreateStudent()
{
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("stud_"+ts+"@gmail.com");
stud.setPhone(new PhoneNumber("123-456-7890"));
Student student = studentService.createStudent(stud);
assertNotNull(student);
assertEquals("stud_"+ts, student.getName());
assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
System.out.println("Created Student:"+student);
}
@Test
public void testCreateStudentWithMap()
{
Map<String, Object> studMap = new HashMap<String, Object>();
long ts = System.currentTimeMillis();
studMap.put("name","stud_"+ts);
studMap.put("email","stud_"+ts+"@gmail.com");
studMap.put("phone",null);
studentService.createStudentWithMap(studMap);
}
@Test
public void testUpdateStudent()
{
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setStudId(2);
stud.setName("stud_"+ts);
stud.setEmail("stud_"+ts+"@gmail.com");
Student updatedStudent = studentService.updateStudent(stud);
assertNotNull(updatedStudent);
assertEquals("stud_"+ts, updatedStudent.getName());
assertEquals("stud_"+ts+"@gmail.com", updatedStudent.getEmail());
}
@Test
public void testDeleteStudent()
{
boolean deleteStudent = studentService.deleteStudent(3);
assertTrue(deleteStudent);
System.out.println("deleteStudent:"+deleteStudent);
}
}
================================================
FILE: chapter03/src/test/java/com/mybatis3/services/TestDataPopulator.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.util.MyBatisUtil;;
/**
* @author Siva
*
*/
public class TestDataPopulator
{
private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
public static void main(String[] args) {
initDatabase();
}
public static void initDatabase()
{
Connection connection = null;
Reader reader = null;
try {
connection = MyBatisUtil.getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
reader = Resources.getResourceAsReader("sql/drop_tables.sql");
scriptRunner.runScript(reader);
logger.info("drop_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/create_tables.sql");
scriptRunner.runScript(reader );
logger.info("create_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/sample_data.sql");
scriptRunner.runScript(reader );
logger.info("sample_data.sql executed successfully");
connection.commit();
reader.close();
scriptRunner.closeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
================================================
FILE: chapter03/src/test/java/com/mybatis3/services/TutorServiceTest.java
================================================
package com.mybatis3.services;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.Course;
import com.mybatis3.domain.Tutor;
public class TutorServiceTest
{
private static TutorService tutorService;
@BeforeClass
public static void setup()
{
TestDataPopulator.initDatabase();
tutorService = new TutorService();
}
@AfterClass
public static void teardown()
{
tutorService = null;
}
@Test
public void testFindTutorById() {
Tutor tutor = tutorService.findTutorById(1);
Assert.assertNotNull(tutor);
List<Course> courses = tutor.getCourses();
Assert.assertNotNull(courses);
for (Course course : courses)
{
Assert.assertNotNull(course);
System.out.println(course);
}
}
}
================================================
FILE: chapter04/README.txt
================================================
Chapter 4: SQL Mappers using Annotations
========================================
This chapter describes mapping SQL statements and query results to java beans in SQL Mappers using Annotation based approach.
Topics covered:
• CRUD Mapping
• ResultSet Mapping
• One-To-One, One-To-Many mappings
• Dynamic SQL mapping
How to Run:
Update the database properties in application.properties file.
You can run the JUnit tests in src/test/java folder.
In JUnit Tests we have Database Initialization logic to setup sample data.
public class StudentServiceTest
{
@BeforeClass
public static void setup() {
studentService = new StudentService();
TestDataPopulator.initDatabase(); // this will drop and re-create database and populates sample data.
}
}
================================================
FILE: chapter04/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mybatis3</groupId>
<artifactId>chapter04</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>chapter04</name>
<url>http://www.mybatis.org</url>
<description>MyBatis Book Chapter 04</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.11</junit.version>
<slf4j.version>1.7.5</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.2.2</mybatis.version>
<mysql.version>5.1.21</mysql.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
================================================
FILE: chapter04/src/main/java/com/mybatis3/domain/Address.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class Address implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer addrId;
private String street;
private String city;
private String state;
private String zip;
private String country;
@Override
public String toString() {
return "Address [addrId=" + addrId + ", street=" + street + ", city=" + city
+ ", state=" + state + ", zip=" + zip + ", country=" + country
+ "]";
}
public Address()
{
}
public Address(Integer addrId)
{
this.addrId = addrId;
}
public Address(Integer addrId, String street, String city, String state,
String zip, String country)
{
this.addrId = addrId;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
}
public Integer getAddrId() {
return addrId;
}
public void setAddrId(Integer addrId) {
this.addrId = addrId;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getZip()
{
return zip;
}
public void setZip(String zip)
{
this.zip = zip;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/domain/Course.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Siva
*
*/
public class Course implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer courseId;
private String name;
private String description;
private Date startDate;
private Date endDate;
private Tutor tutor;
private List<Student> students;
@Override
public String toString() {
return "Course [courseId=" + courseId + ", name=" + name + ", description="
+ description + ", startDate=" + startDate + ", endDate="
+ endDate + ", tutor=" + tutor + ", students=" + students + "]";
}
public Integer getCourseId()
{
return courseId;
}
public void setCourseId(Integer id)
{
this.courseId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Date getStartDate()
{
return startDate;
}
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
public Date getEndDate()
{
return endDate;
}
public void setEndDate(Date endDate)
{
this.endDate = endDate;
}
public List<Student> getStudents()
{
if(students == null){
students = new ArrayList<Student>(0);
}
return students;
}
public void setStudents(List<Student> students)
{
this.students = students;
}
public Tutor getTutor() {
return tutor;
}
public void setTutor(Tutor tutor) {
this.tutor = tutor;
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/domain/PhoneNumber.java
================================================
/**
*
*/
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class PhoneNumber implements Serializable
{
private static final long serialVersionUID = 1L;
private String countryCode;
private String stateCode;
private String number;
public PhoneNumber() {
}
public PhoneNumber(String countryCode, String stateCode, String number) {
super();
this.countryCode = countryCode;
this.stateCode = stateCode;
this.number = number;
}
public PhoneNumber(String string) {
if(string != null){
String[] parts = string.split("-");
if(parts.length>0) this.countryCode=parts[0];
if(parts.length>1) this.stateCode=parts[1];
if(parts.length>2) this.number=parts[2];
}
}
/*@Override
public String toString() {
return this.getAsString();
}*/
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAsString() {
return countryCode+"-"+stateCode+"-"+number;
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/domain/Student.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class Student implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer studId;
private String name;
private String email;
private PhoneNumber phone;
private Address address;
@Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email=" + email
+ ", phone=" + (phone==null?null:phone.getAsString()) + ", address=" + address + "]";
}
public Student()
{
}
public Student(Integer id)
{
this.studId = id;
}
public Integer getStudId()
{
return studId;
}
public void setStudId(Integer id)
{
this.studId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/domain/Tutor.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
import java.util.List;
/**
* @author Siva
*
*/
public class Tutor implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer tutorId;
private String name;
private String email;
private Address address;
private List<Course> courses;
@Override
public String toString() {
return "Tutor [tutorId=" + tutorId + ", name=" + name + ", email=" + email
+ ", address=" + address + ", courses=" + courses + "]";
}
public Tutor()
{
}
public Tutor(Integer id)
{
this.tutorId = id;
}
public Integer getTutorId()
{
return tutorId;
}
public void setTutorId(Integer id)
{
this.tutorId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Address getAddress()
{
return address;
}
public void setAddress(Address address)
{
this.address = address;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/mappers/AddressMapper.java
================================================
/**
*
*/
package com.mybatis3.mappers;
import org.apache.ibatis.annotations.Select;
import com.mybatis3.domain.Address;
/**
* @author Siva
*
*/
public interface AddressMapper
{
@Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}")
Address selectAddressById(int id);
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/mappers/StudentMapper.java
================================================
package com.mybatis3.mappers;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public interface StudentMapper
{
@Select("select * from students")
@Results({
@Result(id=true, column="stud_id", property="studId"),
@Result(column="name", property="name"),
@Result(column="email", property="email"),
@Result(column="addr_id", property="address.addrId")
})
List<Student> findAllStudents();
@Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students")
List<Map<String,Object>> findAllStudentsMap();
@Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}")
Student findStudentById(Integer id);
@Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}")
Map<String,Object> findStudentMapById(Integer id);
@Select("select stud_id, name, email, a.addr_id, street, city, state, zip, country"+
" FROM students s left outer join addresses a on s.addr_id=a.addr_id"+
" where stud_id=#{studId} ")
@ResultMap("com.mybatis3.mappers.StudentMapper.StudentWithAddressResult")
Student selectStudentWithAddress(int studId);
@Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})")
@Options(useGeneratedKeys=true, keyProperty="studId")
void insertStudent(Student student);
@Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})")
@Options(useGeneratedKeys=true, keyProperty="studId")
void insertStudentWithMap(Map<String, Object> map);
@Update("update students set name=#{name}, email=#{email}, phone=#{phone} where stud_id=#{studId}")
void updateStudent(Student student);
@Delete("delete from students where stud_id=#{studId}")
int deleteStudent(int studId);
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/mappers/TutorMapper.java
================================================
/**
*
*/
package com.mybatis3.mappers;
import java.util.List;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import com.mybatis3.domain.Course;
import com.mybatis3.domain.Tutor;
import com.mybatis3.sqlproviders.TutorDynaSqlProvider;
/**
* @author Siva
*
*/
public interface TutorMapper
{
@Select("select * from courses where tutor_id=#{tutorId}")
@ResultMap("com.mybatis3.mappers.TutorMapper.CourseResult")
List<Course> selectCoursesByTutorId(int tutorId);
@Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tutors t where t.tutor_id=#{tutorId}")
@Results({
@Result(id=true, column="tutor_id", property="tutorId"),
@Result(column="tutor_name", property="name"),
@Result(column="email", property="email"),
@Result(property="address", column="addr_id",
one=@One(select="com.mybatis3.mappers.AddressMapper.selectAddressById")),
@Result(property="courses", column="tutor_id",
many=@Many(select="com.mybatis3.mappers.TutorMapper.selectCoursesByTutorId"))
})
Tutor selectTutorWithCoursesById(int tutorId);
@SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutorsSql")
List<Tutor> findAllTutors();
@SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql")
Tutor findTutorById(int tutorId);
@SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNameAndEmailSql")
Tutor findTutorByNameAndEmail(@Param("name")String name, @Param("email")String email);
@InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor")
@Options(useGeneratedKeys=true, keyProperty="tutorId")
int insertTutor(Tutor tutor);
@UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor")
int updateTutor(Tutor tutor);
@DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor")
int deleteTutor(int tutorId);
@SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorById")
@ResultMap("com.mybatis3.mappers.TutorMapper.TutorResult")
Tutor selectTutorById(int tutorId);
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/services/StudentService.java
================================================
package com.mybatis3.services;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.util.MyBatisUtil;
public class StudentService
{
private Logger logger = LoggerFactory.getLogger(getClass());
public List<Student> findAllStudents()
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
return StudentMapper.findAllStudents();
} finally {
sqlSession.close();
}
}
public Student findStudentById(Integer id)
{
logger.debug("findStudentById :"+id);
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(id);
} finally {
sqlSession.close();
}
}
public Student findStudentWithAddressById(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.selectStudentWithAddress(id);
} finally {
sqlSession.close();
}
}
public Student createStudent(Student student) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.insertStudent(student);
sqlSession.commit();
return student;
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public void createStudentWithMap(Map<String, Object> studentDataMap) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.insertStudentWithMap(studentDataMap);
sqlSession.commit();
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public Student updateStudent(Student student) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.updateStudent(student);
sqlSession.commit();
return student;
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public boolean deleteStudent(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int count = mapper.deleteStudent(id);
sqlSession.commit();
return count > 0;
}
catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
finally {
sqlSession.close();
}
}
public Map<String, Object> findStudentMapById(int id) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentMapById(id);
} finally {
sqlSession.close();
}
}
public List<Map<String, Object>> findAllStudentsMap() {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class);
return StudentMapper.findAllStudentsMap();
} finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/services/TutorService.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.mybatis3.domain.Tutor;
import com.mybatis3.mappers.TutorMapper;
import com.mybatis3.util.MyBatisUtil;
/**
* @author Siva
*
*/
public class TutorService
{
public List<Tutor> findAllTutors()
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
return mapper.findAllTutors();
} finally {
sqlSession.close();
}
}
public Tutor findTutorById(int tutorId)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
return mapper.findTutorById(tutorId);
} finally {
sqlSession.close();
}
}
public Tutor findTutorByNameAndEmail(String name, String email)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
return mapper.findTutorByNameAndEmail(name, email);
} finally {
sqlSession.close();
}
}
public Tutor createTutor(Tutor tutor)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
mapper.insertTutor(tutor);
sqlSession.commit();
} finally {
sqlSession.close();
}
return tutor;
}
public Tutor updateTutor(Tutor tutor)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
mapper.updateTutor(tutor);
sqlSession.commit();
} finally {
sqlSession.close();
}
return tutor;
}
public boolean deleteTutor(int tutorId)
{
boolean deleted = false;
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
int nor = mapper.deleteTutor(tutorId);
deleted = (nor == 1);
sqlSession.commit();
} finally {
sqlSession.close();
}
return deleted;
}
public Tutor selectTutorById(int tutorId)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
return mapper.selectTutorById(tutorId);
} finally {
sqlSession.close();
}
}
public Tutor selectTutorWithCoursesById(int tutorId) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
return mapper.selectTutorWithCoursesById(tutorId);
}
finally {
sqlSession.close();
}
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java
================================================
/**
*
*/
package com.mybatis3.sqlproviders;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import com.mybatis3.domain.Tutor;
/**
* @author Siva
*
*/
public class TutorDynaSqlProvider
{
public String findAllTutorsSql()
{
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
}}.toString();
}
public String findTutorByIdSql(final int tutorId)
{
/*return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("tutor_id = #{tutorId}");
}}.toString();*/
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("tutor_id="+tutorId);
}}.toString();
}
public String findTutorByNameAndEmailSql(Map<String, Object> map)
{
//String name = (String) map.get("name");
//String email = (String) map.get("email");
//System.err.println(name+":"+email);
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("name=#{name} AND email=#{email}");
}}.toString();
}
public String insertTutor(final Tutor tutor) {
return new SQL() {{
INSERT_INTO("TUTORS");
if (tutor.getName() != null) {
VALUES("NAME", "#{name}");
}
if (tutor.getEmail() != null) {
VALUES("EMAIL", "#{email}");
}
}}.toString();
}
public String updateTutor(final Tutor tutor)
{
return new SQL() {{
UPDATE("TUTORS");
if (tutor.getName() != null) {
SET("NAME = #{name}");
}
if (tutor.getEmail() != null) {
SET("EMAIL = #{email}");
}
WHERE("TUTOR_ID = #{tutorId}");
}}.toString();
}
public String deleteTutor(int tutorId)
{
return new SQL() {{
DELETE_FROM("TUTORS");
WHERE("TUTOR_ID = #{tutorId}");
}}.toString();
}
public String selectTutorById()
{
return new SQL() {{
SELECT("t.tutor_id, t.name as tutor_name, email");
SELECT("a.addr_id, street, city, state, zip, country");
SELECT("course_id, c.name as course_name, description, start_date, end_date");
FROM("TUTORS t");
LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id");
LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id");
WHERE("t.TUTOR_ID = #{id}");
}}.toString();
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
================================================
/**
*
*/
package com.mybatis3.typehandlers;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.mybatis3.domain.PhoneNumber;
/**
* @author Siva
*
*/
public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.getAsString());
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return new PhoneNumber(rs.getString(columnName));
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return new PhoneNumber(rs.getString(columnIndex));
}
@Override
public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return new PhoneNumber(cs.getString(columnIndex));
}
}
================================================
FILE: chapter04/src/main/java/com/mybatis3/util/MyBatisUtil.java
================================================
package com.mybatis3.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @author Siva
*
*/
public class MyBatisUtil
{
private static SqlSessionFactory sqlSessionFactory;
private static final Properties PROPERTIES = new Properties();
static
{
try {
InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection()
{
String driver = PROPERTIES.getProperty("jdbc.driverClassName");
String url = PROPERTIES.getProperty("jdbc.url");
String username = PROPERTIES.getProperty("jdbc.username");
String password = PROPERTIES.getProperty("jdbc.password");
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return connection;
}
public static SqlSessionFactory getSqlSessionFactory()
{
if(sqlSessionFactory==null)
{
InputStream inputStream;
try
{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e)
{
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
}
================================================
FILE: chapter04/src/main/resources/application.properties
================================================
################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/elearning
jdbc.username=root
jdbc.password=admin
================================================
FILE: chapter04/src/main/resources/com/mybatis3/mappers/StudentMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.StudentMapper">
<resultMap type="Address" id="AddressResult">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</resultMap>
<resultMap type="Student" id="StudentWithAddressResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<association property="address" resultMap="AddressResult"/>
</resultMap>
</mapper>
================================================
FILE: chapter04/src/main/resources/com/mybatis3/mappers/TutorMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.TutorMapper">
<resultMap type="Address" id="AddressResult">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</resultMap>
<resultMap type="Course" id="CourseResult">
<id column="course_id" property="courseId"/>
<result column="course_name" property="name"/>
<result column="description" property="description"/>
<result column="start_date" property="startDate"/>
<result column="end_date" property="endDate"/>
</resultMap>
<resultMap type="Tutor" id="TutorResult">
<id column="tutor_id" property="tutorId"/>
<result column="tutor_name" property="name"/>
<result column="email" property="email"/>
<association property="address" resultMap="AddressResult"/>
<collection property="courses" resultMap="CourseResult"></collection>
</resultMap>
</mapper>
================================================
FILE: chapter04/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
================================================
FILE: chapter04/src/main/resources/mybatis-config.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="application.properties"/>
<typeAliases>
<package name="com.mybatis3.domain"/>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.mybatis3.mappers"/>
</mappers>
</configuration>
================================================
FILE: chapter04/src/main/resources/sql/create_tables.sql
================================================
CREATE TABLE ADDRESSES
(
ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
STREET VARCHAR(50) NOT NULL,
CITY VARCHAR(50) NOT NULL,
STATE VARCHAR(50) NOT NULL,
ZIP VARCHAR(10) DEFAULT NULL,
COUNTRY VARCHAR(50) NOT NULL,
PRIMARY KEY (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE STUDENTS
(
STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
GENDER VARCHAR(6) DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (STUD_ID),
UNIQUE KEY UK_EMAIL (EMAIL),
CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE TUTORS
(
TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
GENDER VARCHAR(6) DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (TUTOR_ID),
UNIQUE KEY UK_EMAIL (EMAIL),
CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSES
(
COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
DESCRIPTION VARCHAR(512) DEFAULT NULL,
START_DATE DATE DEFAULT NULL,
END_DATE DATE DEFAULT NULL,
TUTOR_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID),
CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSE_ENROLLMENT
(
COURSE_ID INT(11) NOT NULL,
STUD_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID,STUD_ID),
CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
================================================
FILE: chapter04/src/main/resources/sql/drop_tables.sql
================================================
DROP TABLE IF EXISTS USER_PICS;
DROP TABLE IF EXISTS COURSE_ENROLLMENT;
DROP TABLE IF EXISTS COURSES;
DROP TABLE IF EXISTS TUTORS;
DROP TABLE IF EXISTS STUDENTS;
DROP TABLE IF EXISTS ADDRESSES;
================================================
FILE: chapter04/src/main/resources/sql/sample_data.sql
================================================
--Sample data for table ADDRESSES
INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
(1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
(2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
(3,'710 N Cable Rd','Lima','OH','45825','Allen'),
(4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
-- Sample data for table STUDENTS
INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,GENDER,BIO,PIC,ADDR_ID) VALUES
(1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25','MALE',NULL,NULL,3),
(2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15','MALE',NULL,NULL,4);
-- Sample data for table TUTORS
INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,GENDER,BIO,PIC,ADDR_ID) VALUES
(1,'John','john@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
(2,'Ken','ken@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
(3,'Paul','paul@gmail.com','123-321-4444','1981-03-15','FEMALE',NULL,NULL,2),
(4,'Mike','mike@gmail.com','123-321-4444','1981-03-15','MALE',NULL,NULL,2);
-- Sample data for table courses
INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
(1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
(2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
(3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
-- Sample data for table COURSE_ENROLLMENT
INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
(1,1),
(1,2),
(2,2);
================================================
FILE: chapter04/src/test/java/com/mybatis3/services/StudentServiceTest.java
================================================
package com.mybatis3.services;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.PhoneNumber;
import com.mybatis3.domain.Student;
public class StudentServiceTest
{
private static StudentService studentService;
@BeforeClass
public static void setup() {
studentService = new StudentService();
TestDataPopulator.initDatabase();
}
@AfterClass
public static void teardown() {
studentService = null;
}
@Test
public void testFindAllStudents() {
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
System.err.println(student);
}
}
@Test
public void testFindStudentById() {
Student student = studentService.findStudentById(1);
System.err.println(student);
System.err.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
}
@Test
public void testFindStudentWithAddressById() {
Student student = studentService.findStudentWithAddressById(2);
assertNotNull(student);
System.out.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
}
@Test
public void testCreateStudent() {
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("stud_"+ts+"@gmail.com");
stud.setPhone(new PhoneNumber("123-456-7890"));
Student student = studentService.createStudent(stud);
assertNotNull(student);
assertEquals("stud_"+ts, student.getName());
assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
System.err.println("CreatedStudent: "+student);
}
@Test
public void testCreateStudentWithMap() {
Map<String, Object> studMap = new HashMap<String, Object>();
long ts = System.currentTimeMillis();
studMap.put("name","stud_"+ts);
studMap.put("email","stud_"+ts+"@gmail.com");
studMap.put("phone",null);
studentService.createStudentWithMap(studMap);
}
@Test
public void testUpdateStudent() {
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setStudId(2);
stud.setName("studddd_"+ts);
stud.setEmail("studddd_"+ts+"@gmail.com");
Student student = studentService.updateStudent(stud);
assertNotNull(student);
assertEquals("studddd_"+ts, student.getName());
assertEquals("studddd_"+ts+"@gmail.com", student.getEmail());
assertEquals(new Integer(2), student.getStudId());
System.out.println("UpdatedStudent: "+student);
}
@Test
public void testDeleteStudent() {
boolean deleted = studentService.deleteStudent(3);
assertTrue(deleted);
System.err.println("deleteStudent:"+deleted);
}
@Test
public void testFindStudentMapById() {
Map<String, Object> studentMap = studentService.findStudentMapById(1);
System.err.println(studentMap);
}
@Test
public void testFindAllStudentsMap() {
List<Map<String,Object>> studentMapList = studentService.findAllStudentsMap();
for(Map<String,Object> studentMap : studentMapList)
{
System.out.println("id :"+studentMap.get("id"));
System.out.println("name :"+studentMap.get("name"));
System.out.println("email :"+studentMap.get("email"));
System.out.println("phone :"+studentMap.get("phone"));
}
}
}
================================================
FILE: chapter04/src/test/java/com/mybatis3/services/TestDataPopulator.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.util.MyBatisUtil;
/**
* @author Siva
*
*/
public class TestDataPopulator
{
private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
public static void main(String[] args) {
initDatabase();
}
public static void initDatabase()
{
Connection connection = null;
Reader reader = null;
try {
connection = MyBatisUtil.getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
reader = Resources.getResourceAsReader("sql/drop_tables.sql");
scriptRunner.runScript(reader);
logger.info("drop_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/create_tables.sql");
scriptRunner.runScript(reader );
logger.info("create_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/sample_data.sql");
scriptRunner.runScript(reader );
logger.info("sample_data.sql executed successfully");
connection.commit();
reader.close();
scriptRunner.closeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
================================================
FILE: chapter04/src/test/java/com/mybatis3/services/TutorServiceTest.java
================================================
package com.mybatis3.services;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatis3.domain.Tutor;
public class TutorServiceTest
{
private static TutorService tutorService;
@BeforeClass
public static void setup() {
tutorService = new TutorService();
TestDataPopulator.initDatabase();
}
@AfterClass
public static void teardown() {
tutorService = null;
}
@Test
public void testFindAllTutors() {
List<Tutor> tutors = tutorService.findAllTutors();
assertNotNull(tutors);
for (Tutor tutor : tutors)
{
System.err.println(tutor);
}
}
@Test
public void testFindTutorById() {
Tutor tutor = tutorService.findTutorById(1);
assertNotNull(tutor);
System.err.println(tutor);
}
@Test
public void testFindTutorByNameAndEmail() {
Tutor tutor = tutorService.findTutorByNameAndEmail("Paul", "paul@gmail.com");
assertNotNull(tutor);
System.err.println(tutor);
}
@Test
public void testCreateTutor() {
Tutor tutor = new Tutor();
tutor.setName("siva");
tutor.setEmail("siva@gmail.com");
tutor = tutorService.createTutor(tutor);
assertNotNull(tutor);
System.err.println(tutor.getTutorId());
}
@Test
public void testUpdateTutor() {
Tutor tutor = new Tutor();
tutor.setTutorId(1);
tutor.setName("sivaprasad");
tutor.setEmail("sivaprasad@gmail.com");
tutor = tutorService.updateTutor(tutor);
Tutor updTutor = tutorService.findTutorById(1);
assertNotNull(updTutor);
System.err.println(updTutor);
}
@Test
public void testDeleteTutor() {
boolean deleted = tutorService.deleteTutor(4);
assertTrue(deleted);
}
@Test
public void testSelectTutorById() {
Tutor tutor = tutorService.selectTutorById(1);
assertNotNull(tutor);
System.err.println(tutor);
}
@Test
public void testSelectTutorWithCoursesById() {
Tutor tutor = tutorService.selectTutorWithCoursesById(1);
assertNotNull(tutor);
System.err.println(tutor);
}
}
================================================
FILE: chapter05/README.txt
================================================
Chapter 5: Integration with Spring
This chapter explains how to integration MyBatis with Spring framework.
Topics covered:
. Configuring MyBatis in Spring ApplicationContext
. Injecting SqlSession and SQL Mappers
. Transaction Management using Spring
How to Run:
Update the database properties in application.properties file.
You can run the JUnit tests in src/test/java folder.
In JUnit Tests we have Database Initialization logic to setup sample data.
public class StudentServiceTest
{
@BeforeClass
public static void setup() {
studentService = new StudentService();
TestDataPopulator.initDatabase(); // this will drop and re-create database and populates sample data.
}
}
================================================
FILE: chapter05/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mybatis3</groupId>
<artifactId>chapter05</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>chapter04</name>
<url>http://www.mybatis.org</url>
<description>MyBatis Book Chapter 05</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.11</junit.version>
<slf4j.version>1.7.5</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.2.2</mybatis.version>
<mybatis-spring.version>1.2.0</mybatis-spring.version>
<mysql.version>5.1.21</mysql.version>
<spring.version>3.1.3.RELEASE</spring.version>
<aspectj.version>1.6.8</aspectj.version>
<cglib.version>2.2</cglib.version>
<commons.dbcp.version>1.4</commons.dbcp.version>
<commons.pool.version>1.6</commons.pool.version>
<commons.lang.version>2.5</commons.lang.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons.dbcp.version}</version>
</dependency>
</dependencies>
</project>
================================================
FILE: chapter05/src/main/java/com/mybatis3/config/AppConfig.java
================================================
package com.mybatis3.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/*
import javax.sql.DataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
*/
/**
* @author Siva
*
*/
@Configuration
@MapperScan(value="com.mybatis3.mappers")
public class AppConfig
{
/*
@Bean
public DataSource dataSource() {
return new PooledDataSource("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/elearning",
"root", "admin");
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
*/
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/domain/Address.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class Address implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer addrId;
private String street;
private String city;
private String state;
private String zip;
private String country;
@Override
public String toString() {
return "Address [addrId=" + addrId + ", street=" + street + ", city=" + city
+ ", state=" + state + ", zip=" + zip + ", country=" + country
+ "]";
}
public Address()
{
}
public Address(Integer addrId)
{
this.addrId = addrId;
}
public Address(Integer addrId, String street, String city, String state,
String zip, String country)
{
this.addrId = addrId;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
}
public Integer getAddrId() {
return addrId;
}
public void setAddrId(Integer addrId) {
this.addrId = addrId;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getZip()
{
return zip;
}
public void setZip(String zip)
{
this.zip = zip;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/domain/Course.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Siva
*
*/
public class Course implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer courseId;
private String name;
private String description;
private Date startDate;
private Date endDate;
private Tutor tutor;
private List<Student> students;
@Override
public String toString() {
return "Course [courseId=" + courseId + ", name=" + name + ", description="
+ description + ", startDate=" + startDate + ", endDate="
+ endDate + ", tutor=" + tutor + ", students=" + students + "]";
}
public Integer getCourseId()
{
return courseId;
}
public void setCourseId(Integer id)
{
this.courseId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Date getStartDate()
{
return startDate;
}
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
public Date getEndDate()
{
return endDate;
}
public void setEndDate(Date endDate)
{
this.endDate = endDate;
}
public List<Student> getStudents()
{
if(students == null){
students = new ArrayList<Student>(0);
}
return students;
}
public void setStudents(List<Student> students)
{
this.students = students;
}
public Tutor getTutor() {
return tutor;
}
public void setTutor(Tutor tutor) {
this.tutor = tutor;
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/domain/PhoneNumber.java
================================================
/**
*
*/
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class PhoneNumber implements Serializable
{
private static final long serialVersionUID = 1L;
private String countryCode;
private String stateCode;
private String number;
public PhoneNumber() {
}
public PhoneNumber(String countryCode, String stateCode, String number) {
super();
this.countryCode = countryCode;
this.stateCode = stateCode;
this.number = number;
}
public PhoneNumber(String string) {
if(string != null){
String[] parts = string.split("-");
if(parts.length>0) this.countryCode=parts[0];
if(parts.length>1) this.stateCode=parts[1];
if(parts.length>2) this.number=parts[2];
}
}
/*@Override
public String toString() {
return this.getAsString();
}*/
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAsString() {
return countryCode+"-"+stateCode+"-"+number;
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/domain/Student.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
/**
* @author Siva
*
*/
public class Student implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer studId;
private String name;
private String email;
private PhoneNumber phone;
private Address address;
@Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email=" + email
+ ", phone=" + (phone==null?null:phone.getAsString()) + ", address=" + address + "]";
}
public Student()
{
}
public Student(Integer id)
{
this.studId = id;
}
public Integer getStudId()
{
return studId;
}
public void setStudId(Integer id)
{
this.studId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/domain/Tutor.java
================================================
package com.mybatis3.domain;
import java.io.Serializable;
import java.util.List;
/**
* @author Siva
*
*/
public class Tutor implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer tutorId;
private String name;
private String email;
private Address address;
private List<Course> courses;
@Override
public String toString() {
return "Tutor [tutorId=" + tutorId + ", name=" + name + ", email=" + email
+ ", address=" + address + ", courses=" + courses + "]";
}
public Tutor()
{
}
public Tutor(Integer id)
{
this.tutorId = id;
}
public Integer getTutorId()
{
return tutorId;
}
public void setTutorId(Integer id)
{
this.tutorId = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Address getAddress()
{
return address;
}
public void setAddress(Address address)
{
this.address = address;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/mappers/AddressMapper.java
================================================
/**
*
*/
package com.mybatis3.mappers;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import com.mybatis3.domain.Address;
/**
* @author Siva
*
*/
public interface AddressMapper
{
@Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}")
Address selectAddressById(int id);
@Insert("insert into addresses(street, city, state, zip, country) values(#{street},#{city},#{state},#{zip},#{country})")
int insertAddress(Address address);
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/mappers/StudentMapper.java
================================================
package com.mybatis3.mappers;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.mybatis3.domain.Student;
/**
* @author Siva
*
*/
public interface StudentMapper
{
@Select("select * from students")
@Results({
@Result(id=true, column="stud_id", property="studId"),
@Result(column="name", property="name"),
@Result(column="email", property="email"),
@Result(column="addr_id", property="address.addrId")
})
List<Student> findAllStudents();
@Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students")
List<Map<String,Object>> findAllStudentsMap();
@Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}")
Student findStudentById(Integer id);
@Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}")
Map<String,Object> findStudentMapById(Integer id);
@Select("select stud_id, name, email, a.addr_id, street, city, state, zip, country"+
" FROM students s left outer join addresses a on s.addr_id=a.addr_id"+
" where stud_id=#{studId} ")
@ResultMap("com.mybatis3.mappers.StudentMapper.StudentWithAddressResult")
Student selectStudentWithAddress(int studId);
@Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})")
@Options(useGeneratedKeys=true, keyProperty="studId")
void insertStudent(Student student);
@Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})")
@Options(useGeneratedKeys=true, keyProperty="studId")
void insertStudentWithMap(Map<String, Object> map);
@Update("update students set name=#{name}, email=#{email}, phone=#{phone} where stud_id=#{studId}")
void updateStudent(Student student);
@Delete("delete from students where stud_id=#{studId}")
int deleteStudent(int studId);
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/mappers/TutorMapper.java
================================================
/**
*
*/
package com.mybatis3.mappers;
import java.util.List;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import com.mybatis3.domain.Course;
import com.mybatis3.domain.Tutor;
import com.mybatis3.sqlproviders.TutorDynaSqlProvider;
/**
* @author Siva
*
*/
public interface TutorMapper
{
@Select("select * from courses where tutor_id=#{tutorId}")
@ResultMap("com.mybatis3.mappers.TutorMapper.CourseResult")
List<Course> selectCoursesByTutorId(int tutorId);
@Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tutors t where t.tutor_id=#{tutorId}")
@Results({
@Result(id=true, column="tutor_id", property="tutorId"),
@Result(column="tutor_name", property="name"),
@Result(column="email", property="email"),
@Result(property="address", column="addr_id",
one=@One(select="com.mybatis3.mappers.AddressMapper.selectAddressById")),
@Result(property="courses", column="tutor_id",
many=@Many(select="com.mybatis3.mappers.TutorMapper.selectCoursesByTutorId"))
})
Tutor selectTutorWithCoursesById(int tutorId);
@SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutorsSql")
List<Tutor> findAllTutors();
@SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql")
Tutor findTutorById(int tutorId);
@SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNameAndEmailSql")
Tutor findTutorByNameAndEmail(@Param("name")String name, @Param("email")String email);
@InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor")
@Options(useGeneratedKeys=true, keyProperty="tutorId")
int insertTutor(Tutor tutor);
@UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor")
int updateTutor(Tutor tutor);
@DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor")
int deleteTutor(int tutorId);
@SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorById")
@ResultMap("com.mybatis3.mappers.TutorMapper.TutorResult")
Tutor selectTutorById(int tutorId);
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/services/StudentService.java
================================================
package com.mybatis3.services;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mybatis3.domain.Address;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.AddressMapper;
import com.mybatis3.mappers.StudentMapper;
@Service
@Transactional
public class StudentService
{
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private StudentMapper studentMapper;
@Autowired
private AddressMapper addressMapper;
public List<Student> findAllStudents() {
return studentMapper.findAllStudents();
}
public Student findStudentById(Integer id) {
logger.debug("findStudentById :"+id);
return studentMapper.findStudentById(id);
}
public Student findStudentWithAddressById(int id) {
return studentMapper.selectStudentWithAddress(id);
}
public Student createStudent(Student student) {
Address address = student.getAddress();
if(address != null){
addressMapper.insertAddress(address);
}
if(student.getName()==null || student.getName().trim().length()==0){
throw new RuntimeException("Student Name should not be null");
}
studentMapper.insertStudent(student);
return student;
}
public void createStudentWithMap(Map<String, Object> studentDataMap) {
studentMapper.insertStudentWithMap(studentDataMap);
}
public Student updateStudent(Student student) {
studentMapper.updateStudent(student);
return student;
}
public boolean deleteStudent(int id) {
int count = studentMapper.deleteStudent(id);
return count > 0;
}
public Map<String, Object> findStudentMapById(int id) {
return studentMapper.findStudentMapById(id);
}
public List<Map<String, Object>> findAllStudentsMap() {
return studentMapper.findAllStudentsMap();
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/services/TutorService.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mybatis3.domain.Tutor;
import com.mybatis3.mappers.TutorMapper;
/**
* @author Siva
*
*/
@Service
@Transactional
public class TutorService
{
@Autowired
private SqlSession sqlSession;
private TutorMapper getTutorMapper(){
return sqlSession.getMapper(TutorMapper.class);
}
public List<Tutor> findAllTutors() {
return getTutorMapper().findAllTutors();
}
public Tutor findTutorById(int tutorId) {
return getTutorMapper().findTutorById(tutorId);
}
public Tutor findTutorByNameAndEmail(String name, String email) {
return getTutorMapper().findTutorByNameAndEmail(name, email);
}
public Tutor createTutor(Tutor tutor) {
getTutorMapper().insertTutor(tutor);
return tutor;
}
public Tutor updateTutor(Tutor tutor) {
getTutorMapper().updateTutor(tutor);
return tutor;
}
public boolean deleteTutor(int tutorId) {
boolean deleted = false;
int nor = getTutorMapper().deleteTutor(tutorId);
deleted = (nor == 1);
return deleted;
}
public Tutor selectTutorById(int tutorId) {
return getTutorMapper().selectTutorById(tutorId);
}
public Tutor selectTutorWithCoursesById(int tutorId) {
return getTutorMapper().selectTutorWithCoursesById(tutorId);
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java
================================================
/**
*
*/
package com.mybatis3.sqlproviders;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import com.mybatis3.domain.Tutor;
/**
* @author Siva
*
*/
public class TutorDynaSqlProvider
{
public String findAllTutorsSql()
{
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
}}.toString();
}
public String findTutorByIdSql(final int tutorId)
{
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("tutor_id="+tutorId);
}}.toString();
}
public String findTutorByNameAndEmailSql(Map<String, Object> map)
{
//String name = (String) map.get("name");
//String email = (String) map.get("email");
//System.err.println(name+":"+email);
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("name=#{name} AND email=#{email}");
}}.toString();
}
public String insertTutor(final Tutor tutor) {
return new SQL() {{
INSERT_INTO("TUTORS");
if (tutor.getName() != null) {
VALUES("NAME", "#{name}");
}
if (tutor.getEmail() != null) {
VALUES("EMAIL", "#{email}");
}
}}.toString();
}
public String updateTutor(final Tutor tutor)
{
return new SQL() {{
UPDATE("TUTORS");
if (tutor.getName() != null) {
SET("NAME = #{name}");
}
if (tutor.getEmail() != null) {
SET("EMAIL = #{email}");
}
WHERE("TUTOR_ID = #{tutorId}");
}}.toString();
}
public String deleteTutor(int tutorId)
{
return new SQL() {{
DELETE_FROM("TUTORS");
WHERE("TUTOR_ID = #{tutorId}");
}}.toString();
}
public String selectTutorById()
{
return new SQL() {{
SELECT("t.tutor_id, t.name as tutor_name, email, a.addr_id, street, city, state, zip, country,course_id, c.name as course_name, description, start_date, end_date");
FROM("TUTORS t");
LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id");
LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id");
WHERE("t.TUTOR_ID = #{tutorId}");
}}.toString();
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
================================================
/**
*
*/
package com.mybatis3.typehandlers;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.mybatis3.domain.PhoneNumber;
/**
* @author Siva
*
*/
public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.getAsString());
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return new PhoneNumber(rs.getString(columnName));
}
@Override
public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return new PhoneNumber(rs.getString(columnIndex));
}
@Override
public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return new PhoneNumber(cs.getString(columnIndex));
}
}
================================================
FILE: chapter05/src/main/java/com/mybatis3/util/MyBatisUtil.java
================================================
package com.mybatis3.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @author Siva
*
*/
public class MyBatisUtil
{
private static SqlSessionFactory sqlSessionFactory;
private static final Properties PROPERTIES = new Properties();
static
{
try {
InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection()
{
String driver = PROPERTIES.getProperty("jdbc.driverClassName");
String url = PROPERTIES.getProperty("jdbc.url");
String username = PROPERTIES.getProperty("jdbc.username");
String password = PROPERTIES.getProperty("jdbc.password");
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return connection;
}
public static SqlSessionFactory getSqlSessionFactory()
{
if(sqlSessionFactory==null)
{
InputStream inputStream;
try
{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e)
{
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
}
================================================
FILE: chapter05/src/main/resources/application.properties
================================================
################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/elearning
jdbc.username=root
jdbc.password=admin
================================================
FILE: chapter05/src/main/resources/applicationContext.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<context:annotation-config />
<context:component-scan base-package="com.mybatis3" />
<context:property-placeholder location="classpath:application.properties" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- <mybatis:scan base-package="com.mybatis3.mappers"/> -->
<!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mybatis3.mappers" />
</bean> -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.mybatis3.domain"/>
<property name="typeHandlersPackage" value="com.mybatis3.typehandlers"/>
<property name="mapperLocations" value="classpath*:com/mybatis3/**/*.xml" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
================================================
FILE: chapter05/src/main/resources/com/mybatis3/mappers/StudentMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.StudentMapper">
<resultMap type="Address" id="AddressResult">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</resultMap>
<resultMap type="Student" id="StudentWithAddressResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<association property="address" resultMap="AddressResult"/>
</resultMap>
</mapper>
================================================
FILE: chapter05/src/main/resources/com/mybatis3/mappers/TutorMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis3.mappers.TutorMapper">
<resultMap type="Address" id="AddressResult">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</resultMap>
<resultMap type="Course" id="CourseResult">
<id column="course_id" property="courseId"/>
<result column="course_name" property="name"/>
<result column="description" property="description"/>
<result column="start_date" property="startDate"/>
<result column="end_date" property="endDate"/>
</resultMap>
<resultMap type="Tutor" id="TutorResult">
<id column="tutor_id" property="tutorId"/>
<result column="tutor_name" property="name"/>
<result column="email" property="email"/>
<association property="address" resultMap="AddressResult"/>
<collection property="courses" resultMap="CourseResult"></collection>
</resultMap>
</mapper>
================================================
FILE: chapter05/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
================================================
FILE: chapter05/src/main/resources/sql/create_tables.sql
================================================
CREATE TABLE ADDRESSES
(
ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
STREET VARCHAR(50) NOT NULL,
CITY VARCHAR(50) NOT NULL,
STATE VARCHAR(50) NOT NULL,
ZIP VARCHAR(10) DEFAULT NULL,
COUNTRY VARCHAR(50) NOT NULL,
PRIMARY KEY (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE STUDENTS
(
STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
GENDER VARCHAR(6) DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (STUD_ID),
UNIQUE KEY UK_EMAIL (EMAIL),
CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE TUTORS
(
TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
EMAIL VARCHAR(50) NOT NULL,
PHONE VARCHAR(15) DEFAULT NULL,
DOB DATE DEFAULT NULL,
GENDER VARCHAR(6) DEFAULT NULL,
BIO LONGTEXT DEFAULT NULL,
PIC BLOB DEFAULT NULL,
ADDR_ID INT(11) DEFAULT NULL,
PRIMARY KEY (TUTOR_ID),
UNIQUE KEY UK_EMAIL (EMAIL),
CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSES
(
COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
DESCRIPTION VARCHAR(512) DEFAULT NULL,
START_DATE DATE DEFAULT NULL,
END_DATE DATE DEFAULT NULL,
TUTOR_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID),
CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
CREATE TABLE COURSE_ENROLLMENT
(
COURSE_ID INT(11) NOT NULL,
STUD_ID INT(11) NOT NULL,
PRIMARY KEY (COURSE_ID,STUD_ID),
CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
================================================
FILE: chapter05/src/main/resources/sql/drop_tables.sql
================================================
DROP TABLE IF EXISTS USER_PICS;
DROP TABLE IF EXISTS COURSE_ENROLLMENT;
DROP TABLE IF EXISTS COURSES;
DROP TABLE IF EXISTS TUTORS;
DROP TABLE IF EXISTS STUDENTS;
DROP TABLE IF EXISTS ADDRESSES;
================================================
FILE: chapter05/src/main/resources/sql/sample_data.sql
================================================
--Sample data for table ADDRESSES
INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
(1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
(2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
(3,'710 N Cable Rd','Lima','OH','45825','Allen'),
(4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
-- Sample data for table STUDENTS
INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,GENDER,BIO,PIC,ADDR_ID) VALUES
(1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25','MALE',NULL,NULL,3),
(2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15','MALE',NULL,NULL,4);
-- Sample data for table TUTORS
INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,GENDER,BIO,PIC,ADDR_ID) VALUES
(1,'John','john@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
(2,'Ken','ken@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
(3,'Paul','paul@gmail.com','123-321-4444','1981-03-15','FEMALE',NULL,NULL,2),
(4,'Mike','mike@gmail.com','123-321-4444','1981-03-15','MALE',NULL,NULL,2);
-- Sample data for table courses
INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
(1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
(2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
(3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
-- Sample data for table COURSE_ENROLLMENT
INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
(1,1),
(1,2),
(2,2);
================================================
FILE: chapter05/src/test/java/com/mybatis3/services/StudentServiceTest.java
================================================
package com.mybatis3.services;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mybatis3.domain.Address;
import com.mybatis3.domain.PhoneNumber;
import com.mybatis3.domain.Student;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class StudentServiceTest
{
@Autowired
private StudentService studentService;
@BeforeClass
public static void setup() {
TestDataPopulator.initDatabase();
}
@Test
public void testFindAllStudents() {
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
System.err.println(student);
}
}
@Test
public void testFindStudentById() {
Student student = studentService.findStudentById(1);
System.err.println(student);
System.err.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
}
@Test
public void testFindStudentWithAddressById() {
Student student = studentService.findStudentWithAddressById(2);
assertNotNull(student);
System.out.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
}
@Test
public void testCreateStudent() {
//Address address = new Address();
Address address = new Address(1,"Quaker Ridge Rd.","Bethel","Brooklyn","06801","USA");
/*address.setStreet("Quaker Ridge Rd.");
address.setCity("Bethel");
address.setState("Brooklyn");
address.setZip("06801");
address.setCountry("USA");*/
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("stud_"+ts+"@gmail.com");
stud.setPhone(new PhoneNumber("123-456-7890"));
stud.setAddress(address);
Student student = studentService.createStudent(stud);
assertNotNull(student);
assertEquals("stud_"+ts, student.getName());
assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
System.err.println("CreatedStudent: "+student);
}
@Test(expected=DataAccessException.class)
public void testCreateStudentForException() {
Address address = new Address();
address.setStreet("Quaker Ridge Rd.");
address.setCity("Bethel");
address.setState("Brooklyn");
address.setZip("06801");
address.setCountry("USA");
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("timothy@gmail.com");
stud.setPhone(new PhoneNumber("123-456-7890"));
stud.setAddress(address);
studentService.createStudent(stud);
fail("You should not reach here");
}
@Test
public void testCreateStudentWithMap() {
Map<String, Object> studMap = new HashMap<String, Object>();
long ts = System.currentTimeMillis();
studMap.put("name","stud_"+ts);
studMap.put("email","stud_"+ts+"@gmail.com");
studMap.put("phone",null);
studentService.createStudentWithMap(studMap);
}
@Test
public void testUpdateStudent() {
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setStudId(2);
stud.setName("studddd_"+ts);
stud.setEmail("studddd_"+ts+"@gmail.com");
Student student = studentService.updateStudent(stud);
assertNotNull(student);
assertEquals("studddd_"+ts, student.getName());
assertEquals("studddd_"+ts+"@gmail.com", student.getEmail());
assertEquals(new Integer(2), student.getStudId());
System.out.println("UpdatedStudent: "+student);
}
@Test
public void testDeleteStudent() {
boolean deleted = studentService.deleteStudent(3);
assertTrue(deleted);
System.err.println("deleteStudent:"+deleted);
}
@Test
public void testFindStudentMapById() {
Map<String, Object> studentMap = studentService.findStudentMapById(1);
System.err.println(studentMap);
}
@Test
public void testFindAllStudentsMap() {
List<Map<String,Object>> studentMapList = studentService.findAllStudentsMap();
for(Map<String,Object> studentMap : studentMapList)
{
System.out.println("id :"+studentMap.get("id"));
System.out.println("name :"+studentMap.get("name"));
System.out.println("email :"+studentMap.get("email"));
System.out.println("phone :"+studentMap.get("phone"));
}
}
}
================================================
FILE: chapter05/src/test/java/com/mybatis3/services/TestDataPopulator.java
================================================
/**
*
*/
package com.mybatis3.services;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.util.MyBatisUtil;
/**
* @author Siva
*
*/
public class TestDataPopulator
{
private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
public static void main(String[] args) {
initDatabase();
}
public static void initDatabase()
{
Connection connection = null;
Reader reader = null;
try {
connection = MyBatisUtil.getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
reader = Resources.getResourceAsReader("sql/drop_tables.sql");
scriptRunner.runScript(reader);
logger.info("drop_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/create_tables.sql");
scriptRunner.runScript(reader );
logger.info("create_tables.sql executed successfully");
reader = Resources.getResourceAsReader("sql/sample_data.sql");
scriptRunner.runScript(reader );
logger.info("sample_data.sql executed successfully");
connection.commit();
reader.close();
scriptRunner.closeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
================================================
FILE: chapter05/src/test/java/com/mybatis3/services/TutorServiceTest.java
================================================
package com.mybatis3.services;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mybatis3.domain.Tutor;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TutorServiceTest
{
@Autowired
private TutorService tutorService;
@BeforeClass
public static void setup() {
TestDataPopulator.initDatabase();
}
@Test
public void testFindAllTutors() {
List<Tutor> tutors = tutorService.findAllTutors();
assertNotNull(tutors);
for (Tutor tutor : tutors)
{
System.err.println(tutor);
}
}
@Test
public void testFindTutorById() {
Tutor tutor = tutorService.findTutorById(1);
assertNotNull(tutor);
//System.err.println(tutor);
}
@Test
public void testFindTutorByNameAndEmail() {
Tutor tutor = tutorService.findTutorByNameAndEmail("Paul", "paul@gmail.com");
assertNotNull(tutor);
//System.err.println(tutor);
}
@Test
public void testCreateTutor() {
Tutor tutor = new Tutor();
tutor.setName("siva");
tutor.setEmail("siva@gmail.com");
tutor = tutorService.createTutor(tutor);
assertNotNull(tutor);
}
@Test
public void testUpdateTutor() {
Tutor tutor = new Tutor();
tutor.setTutorId(1);
tutor.setName("sivaprasad");
tutor.setEmail("sivaprasad@gmail.com");
tutor = tutorService.updateTutor(tutor);
Tutor updTutor = tutorService.findTutorById(1);
assertNotNull(updTutor);
System.err.println(updTutor);
}
@Test
public void testDeleteTutor() {
boolean deleted = tutorService.deleteTutor(4);
assertTrue(deleted);
}
@Test
public void testSelectTutorById() {
Tutor tutor = tutorService.selectTutorById(1);
assertNotNull(tutor);
System.err.println(tutor);
}
@Test
public void testSelectTutorWithCoursesById() {
Tutor tutor = tutorService.selectTutorWithCoursesById(1);
assertNotNull(tutor);
System.err.println(tutor);
}
}
================================================
FILE: elearning/README.txt
================================================
This module demonstrate developing a simple web app using MyBatis persistence framework.
================================================
FILE: elearning/pom.xml
================================================
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mybatis3</groupId>
<version>0.0.1</version>
<artifactId>elearning</artifactId>
<packaging>war</packaging>
<name>E-Learning Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.8.2</junit.version>
<slf4j.version>1.6.2</slf4j.version>
<logback.version>1.0.1</logback.version>
<log4j.version>1.2.16</log4j.version>
<spring.version>3.1.0.RELEASE</spring.version>
<mybatis.version>3.2.2</mybatis.version>
<mybatis-spring.version>1.2.0</mybatis-spring.version>
<mybatis-ehcache.version>1.0.0</mybatis-ehcache.version>
<aspectj.version>1.6.8</aspectj.version>
<cglib.version>2.2</cglib.version>
<mysql.version>5.1.18</mysql.version>
<commons.dbcp.version>1.4</commons.dbcp.version>
<commons.pool.version>1.6</commons.pool.version>
<commons.lang.version>2.5</commons.lang.version>
<servlet.version>2.5</servlet.version>
<jsp.version>2.1</jsp.version>
<jstl.version>1.2</jstl.version>
<taglibs-standard.version>1.1.2</taglibs-standard.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
<maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>failsafe-maven-plugin</artifactId>
<version>${maven.failsafe.plugin}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons.dbcp.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.lang.version}</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>${commons.pool.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${taglibs-standard.version}</version>
gitextract_ol89q38l/
├── .gitignore
├── README.md
├── chapter01/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ └── Student.java
│ │ │ ├── mappers/
│ │ │ │ └── StudentMapper.java
│ │ │ ├── services/
│ │ │ │ ├── JdbcStudentService.java
│ │ │ │ └── StudentService.java
│ │ │ └── util/
│ │ │ └── MyBatisSqlSessionFactory.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ └── StudentMapper.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── mybatis3/
│ │ └── services/
│ │ ├── StudentServiceTest.java
│ │ └── TestDataPopulator.java
│ └── resources/
│ └── log4j.properties
├── chapter02/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ └── Student.java
│ │ │ ├── mappers/
│ │ │ │ └── StudentMapper.java
│ │ │ ├── services/
│ │ │ │ └── StudentService.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ ├── DataSourceFactory.java
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ └── StudentMapper.xml
│ │ ├── full-mybatis-config.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── StudentServiceTest.java
│ └── TestDataPopulator.java
├── chapter03/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ ├── Address.java
│ │ │ │ ├── Course.java
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ ├── Student.java
│ │ │ │ └── Tutor.java
│ │ │ ├── mappers/
│ │ │ │ ├── AddressMapper.java
│ │ │ │ ├── CourseMapper.java
│ │ │ │ ├── StudentMapper.java
│ │ │ │ └── TutorMapper.java
│ │ │ ├── services/
│ │ │ │ ├── CourseService.java
│ │ │ │ ├── StudentService.java
│ │ │ │ └── TutorService.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ ├── AddressMapper.xml
│ │ │ ├── CourseMapper.xml
│ │ │ ├── StudentMapper.xml
│ │ │ └── TutorMapper.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── CourseServiceTest.java
│ ├── StudentServiceTest.java
│ ├── TestDataPopulator.java
│ └── TutorServiceTest.java
├── chapter04/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── domain/
│ │ │ │ ├── Address.java
│ │ │ │ ├── Course.java
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ ├── Student.java
│ │ │ │ └── Tutor.java
│ │ │ ├── mappers/
│ │ │ │ ├── AddressMapper.java
│ │ │ │ ├── StudentMapper.java
│ │ │ │ └── TutorMapper.java
│ │ │ ├── services/
│ │ │ │ ├── StudentService.java
│ │ │ │ └── TutorService.java
│ │ │ ├── sqlproviders/
│ │ │ │ └── TutorDynaSqlProvider.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ ├── StudentMapper.xml
│ │ │ └── TutorMapper.xml
│ │ ├── log4j.properties
│ │ ├── mybatis-config.xml
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── StudentServiceTest.java
│ ├── TestDataPopulator.java
│ └── TutorServiceTest.java
├── chapter05/
│ ├── README.txt
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── mybatis3/
│ │ │ ├── config/
│ │ │ │ └── AppConfig.java
│ │ │ ├── domain/
│ │ │ │ ├── Address.java
│ │ │ │ ├── Course.java
│ │ │ │ ├── PhoneNumber.java
│ │ │ │ ├── Student.java
│ │ │ │ └── Tutor.java
│ │ │ ├── mappers/
│ │ │ │ ├── AddressMapper.java
│ │ │ │ ├── StudentMapper.java
│ │ │ │ └── TutorMapper.java
│ │ │ ├── services/
│ │ │ │ ├── StudentService.java
│ │ │ │ └── TutorService.java
│ │ │ ├── sqlproviders/
│ │ │ │ └── TutorDynaSqlProvider.java
│ │ │ ├── typehandlers/
│ │ │ │ └── PhoneTypeHandler.java
│ │ │ └── util/
│ │ │ └── MyBatisUtil.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── applicationContext.xml
│ │ ├── com/
│ │ │ └── mybatis3/
│ │ │ └── mappers/
│ │ │ ├── StudentMapper.xml
│ │ │ └── TutorMapper.xml
│ │ ├── log4j.properties
│ │ └── sql/
│ │ ├── create_tables.sql
│ │ ├── drop_tables.sql
│ │ └── sample_data.sql
│ └── test/
│ └── java/
│ └── com/
│ └── mybatis3/
│ └── services/
│ ├── StudentServiceTest.java
│ ├── TestDataPopulator.java
│ └── TutorServiceTest.java
└── elearning/
├── README.txt
├── pom.xml
└── src/
└── main/
├── resources/
│ └── log4j.properties
└── webapp/
├── WEB-INF/
│ └── web.xml
└── index.jsp
SYMBOL INDEX (572 symbols across 72 files)
FILE: chapter01/src/main/java/com/mybatis3/domain/Student.java
class Student (line 10) | public class Student
method Student (line 17) | public Student() {
method Student (line 21) | public Student(Integer studId) {
method Student (line 25) | public Student(Integer studId, String name, String email, Date dob) {
method toString (line 32) | @Override
method getStudId (line 38) | public Integer getStudId() {
method setStudId (line 41) | public void setStudId(Integer studId) {
method getName (line 44) | public String getName() {
method setName (line 47) | public void setName(String name) {
method getEmail (line 50) | public String getEmail() {
method setEmail (line 53) | public void setEmail(String email) {
method getDob (line 56) | public Date getDob() {
method setDob (line 59) | public void setDob(Date dob) {
FILE: chapter01/src/main/java/com/mybatis3/mappers/StudentMapper.java
type StudentMapper (line 12) | public interface StudentMapper
method findAllStudents (line 15) | List<Student> findAllStudents();
method findStudentById (line 17) | Student findStudentById(Integer id);
method insertStudent (line 19) | void insertStudent(Student student);
method updateStudent (line 21) | void updateStudent(Student student);
FILE: chapter01/src/main/java/com/mybatis3/services/JdbcStudentService.java
class JdbcStudentService (line 18) | public class JdbcStudentService
method main (line 26) | public static void main(String[] args)
method findStudentById (line 48) | public Student findStudentById(int studId)
method createStudent (line 83) | public void createStudent(Student student)
method updateStudent (line 111) | public void updateStudent(Student student)
method getDatabaseConnection (line 140) | protected Connection getDatabaseConnection() throws SQLException
FILE: chapter01/src/main/java/com/mybatis3/services/StudentService.java
class StudentService (line 18) | public class StudentService
method findAllStudents (line 22) | public List<Student> findAllStudents()
method findStudentById (line 33) | public Student findStudentById(Integer studId)
method createStudent (line 46) | public void createStudent(Student student)
method updateStudent (line 58) | public void updateStudent(Student student)
FILE: chapter01/src/main/java/com/mybatis3/util/MyBatisSqlSessionFactory.java
class MyBatisSqlSessionFactory (line 19) | public class MyBatisSqlSessionFactory
method getSqlSessionFactory (line 35) | public static SqlSessionFactory getSqlSessionFactory()
method getSqlSession (line 59) | public static SqlSession getSqlSession()
method getConnection (line 64) | public static Connection getConnection()
FILE: chapter01/src/main/resources/sql/create_tables.sql
type ADDRESSES (line 2) | CREATE TABLE ADDRESSES
type STUDENTS (line 13) | CREATE TABLE STUDENTS
type TUTORS (line 27) | CREATE TABLE TUTORS
type COURSES (line 42) | CREATE TABLE COURSES
type COURSE_ENROLLMENT (line 55) | CREATE TABLE COURSE_ENROLLMENT
type USER_PICS (line 66) | CREATE TABLE USER_PICS
FILE: chapter01/src/test/java/com/mybatis3/services/StudentServiceTest.java
class StudentServiceTest (line 19) | public class StudentServiceTest
method setup (line 23) | @BeforeClass
method teardown (line 29) | @AfterClass
method testFindAllStudents (line 35) | @Test
method testFindStudentById (line 48) | @Test
method testCreateUStudent (line 55) | @Test
method testUpdateStudent (line 71) | @Test
FILE: chapter01/src/test/java/com/mybatis3/services/TestDataPopulator.java
class TestDataPopulator (line 20) | public class TestDataPopulator
method main (line 24) | public static void main(String[] args) {
method initDatabase (line 28) | public static void initDatabase()
FILE: chapter02/src/main/java/com/mybatis3/domain/PhoneNumber.java
class PhoneNumber (line 11) | public class PhoneNumber
method PhoneNumber (line 17) | public PhoneNumber() {
method PhoneNumber (line 20) | public PhoneNumber(String countryCode, String stateCode, String number) {
method PhoneNumber (line 27) | public PhoneNumber(String string) {
method toString (line 37) | @Override
method getCountryCode (line 42) | public String getCountryCode() {
method setCountryCode (line 46) | public void setCountryCode(String countryCode) {
method getStateCode (line 50) | public String getStateCode() {
method setStateCode (line 54) | public void setStateCode(String stateCode) {
method getNumber (line 58) | public String getNumber() {
method setNumber (line 62) | public void setNumber(String number) {
method getAsString (line 66) | public String getAsString() {
FILE: chapter02/src/main/java/com/mybatis3/domain/Student.java
class Student (line 12) | @Alias("Student")
method Student (line 20) | public Student() {
method Student (line 24) | public Student(Integer studId) {
method Student (line 28) | public Student(Integer studId, String name, String email, Date dob) {
method toString (line 35) | @Override
method getStudId (line 41) | public Integer getStudId() {
method setStudId (line 44) | public void setStudId(Integer studId) {
method getName (line 47) | public String getName() {
method setName (line 50) | public void setName(String name) {
method getEmail (line 53) | public String getEmail() {
method setEmail (line 56) | public void setEmail(String email) {
method getDob (line 59) | public Date getDob() {
method setDob (line 62) | public void setDob(Date dob) {
FILE: chapter02/src/main/java/com/mybatis3/mappers/StudentMapper.java
type StudentMapper (line 12) | public interface StudentMapper
method findAllStudents (line 15) | List<Student> findAllStudents();
method findStudentById (line 17) | Student findStudentById(Integer id);
method insertStudent (line 19) | void insertStudent(Student student);
method updateStudent (line 21) | void updateStudent(Student student);
FILE: chapter02/src/main/java/com/mybatis3/services/StudentService.java
class StudentService (line 14) | public class StudentService
method StudentService (line 19) | public StudentService(SqlSessionFactory factory) {
method openSqlSession (line 23) | protected SqlSession openSqlSession()
method findAllStudents (line 27) | public List<Student> findAllStudents()
method findStudentById (line 39) | public Student findStudentById(Integer studId)
method createStudent (line 51) | public Student createStudent(Student student)
method updateStudent (line 64) | public void updateStudent(Student student)
FILE: chapter02/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
class PhoneTypeHandler (line 21) | public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
method setNonNullParameter (line 23) | @Override
method getNullableResult (line 29) | @Override
method getNullableResult (line 35) | @Override
method getNullableResult (line 41) | @Override
FILE: chapter02/src/main/java/com/mybatis3/util/DataSourceFactory.java
class DataSourceFactory (line 20) | public class DataSourceFactory
method getDataSource (line 34) | public static DataSource getDataSource()
method getJNDIDataSource (line 44) | public static DataSource getJNDIDataSource()
FILE: chapter02/src/main/java/com/mybatis3/util/MyBatisUtil.java
class MyBatisUtil (line 25) | public class MyBatisUtil
method getSqlSessionFactoryUsingXML (line 30) | public static SqlSessionFactory getSqlSessionFactoryUsingXML()
method getSqlSessionFactoryUsingJavaAPI (line 47) | public static SqlSessionFactory getSqlSessionFactoryUsingJavaAPI()
FILE: chapter02/src/main/resources/sql/create_tables.sql
type ADDRESSES (line 2) | CREATE TABLE ADDRESSES
type STUDENTS (line 13) | CREATE TABLE STUDENTS
type TUTORS (line 27) | CREATE TABLE TUTORS
type COURSES (line 42) | CREATE TABLE COURSES
type COURSE_ENROLLMENT (line 55) | CREATE TABLE COURSE_ENROLLMENT
type USER_PICS (line 66) | CREATE TABLE USER_PICS
FILE: chapter02/src/test/java/com/mybatis3/services/StudentServiceTest.java
class StudentServiceTest (line 17) | public class StudentServiceTest
method setup (line 21) | @BeforeClass
method teardown (line 35) | @AfterClass
method testFindAllStudents (line 41) | @Test
method testFindStudentById (line 54) | @Test
method testCreateUStudent (line 61) | @Test
method testUpdateStudent (line 76) | @Test
FILE: chapter02/src/test/java/com/mybatis3/services/TestDataPopulator.java
class TestDataPopulator (line 21) | public class TestDataPopulator
method main (line 25) | public static void main(String[] args) {
method initDatabase (line 29) | public static void initDatabase()
FILE: chapter03/src/main/java/com/mybatis3/domain/Address.java
class Address (line 9) | public class Address implements Serializable
method toString (line 20) | @Override
method Address (line 26) | public Address()
method Address (line 29) | public Address(Integer addrId)
method Address (line 33) | public Address(Integer addrId, String street, String city, String state,
method getAddrId (line 43) | public Integer getAddrId() {
method setAddrId (line 46) | public void setAddrId(Integer addrId) {
method getStreet (line 49) | public String getStreet()
method setStreet (line 53) | public void setStreet(String street)
method getCity (line 57) | public String getCity()
method setCity (line 61) | public void setCity(String city)
method getState (line 65) | public String getState()
method setState (line 69) | public void setState(String state)
method getZip (line 73) | public String getZip()
method setZip (line 77) | public void setZip(String zip)
method getCountry (line 81) | public String getCountry()
method setCountry (line 85) | public void setCountry(String country)
FILE: chapter03/src/main/java/com/mybatis3/domain/Course.java
class Course (line 12) | public class Course implements Serializable
method toString (line 24) | @Override
method getCourseId (line 30) | public Integer getCourseId()
method setCourseId (line 34) | public void setCourseId(Integer id)
method getName (line 38) | public String getName()
method setName (line 42) | public void setName(String name)
method getDescription (line 46) | public String getDescription()
method setDescription (line 50) | public void setDescription(String description)
method getStartDate (line 54) | public Date getStartDate()
method setStartDate (line 58) | public void setStartDate(Date startDate)
method getEndDate (line 62) | public Date getEndDate()
method setEndDate (line 66) | public void setEndDate(Date endDate)
method getStudents (line 70) | public List<Student> getStudents()
method setStudents (line 77) | public void setStudents(List<Student> students)
method getTutor (line 81) | public Tutor getTutor() {
method setTutor (line 84) | public void setTutor(Tutor tutor) {
FILE: chapter03/src/main/java/com/mybatis3/domain/PhoneNumber.java
class PhoneNumber (line 13) | public class PhoneNumber implements Serializable
method PhoneNumber (line 21) | public PhoneNumber() {
method PhoneNumber (line 24) | public PhoneNumber(String countryCode, String stateCode, String number) {
method PhoneNumber (line 31) | public PhoneNumber(String string) {
method getCountryCode (line 46) | public String getCountryCode() {
method setCountryCode (line 50) | public void setCountryCode(String countryCode) {
method getStateCode (line 54) | public String getStateCode() {
method setStateCode (line 58) | public void setStateCode(String stateCode) {
method getNumber (line 62) | public String getNumber() {
method setNumber (line 66) | public void setNumber(String number) {
method getAsString (line 70) | public String getAsString() {
FILE: chapter03/src/main/java/com/mybatis3/domain/Student.java
class Student (line 10) | public class Student implements Serializable
method toString (line 19) | @Override
method Student (line 24) | public Student()
method Student (line 27) | public Student(Integer id)
method getStudId (line 31) | public Integer getStudId()
method setStudId (line 35) | public void setStudId(Integer id)
method getName (line 39) | public String getName()
method setName (line 43) | public void setName(String name)
method getEmail (line 47) | public String getEmail()
method setEmail (line 51) | public void setEmail(String email)
method getAddress (line 55) | public Address getAddress() {
method setAddress (line 58) | public void setAddress(Address address) {
method getPhone (line 61) | public PhoneNumber getPhone() {
method setPhone (line 64) | public void setPhone(PhoneNumber phone) {
FILE: chapter03/src/main/java/com/mybatis3/domain/Tutor.java
class Tutor (line 10) | public class Tutor implements Serializable
method toString (line 20) | @Override
method Tutor (line 25) | public Tutor()
method Tutor (line 28) | public Tutor(Integer id)
method getTutorId (line 32) | public Integer getTutorId()
method setTutorId (line 36) | public void setTutorId(Integer id)
method getName (line 40) | public String getName()
method setName (line 44) | public void setName(String name)
method getEmail (line 48) | public String getEmail()
method setEmail (line 52) | public void setEmail(String email)
method getAddress (line 56) | public Address getAddress()
method setAddress (line 60) | public void setAddress(Address address)
method getCourses (line 64) | public List<Course> getCourses() {
method setCourses (line 67) | public void setCourses(List<Course> courses) {
FILE: chapter03/src/main/java/com/mybatis3/mappers/AddressMapper.java
type AddressMapper (line 11) | public interface AddressMapper
method findAddressById (line 13) | Address findAddressById(Integer id);
FILE: chapter03/src/main/java/com/mybatis3/mappers/CourseMapper.java
type CourseMapper (line 14) | public interface CourseMapper
method selectCoursesByTutor (line 17) | List<Course> selectCoursesByTutor(int tutorId);
method searchCourses (line 19) | List<Course> searchCourses(Map<String, Object> map);
method searchCoursesByTutors (line 21) | List<Course> searchCoursesByTutors(Map<String, Object> map);
FILE: chapter03/src/main/java/com/mybatis3/mappers/StudentMapper.java
type StudentMapper (line 14) | public interface StudentMapper
method findAllStudents (line 17) | List<Student> findAllStudents();
method findStudentById (line 19) | Student findStudentById(Integer id);
method selectStudentWithAddress (line 21) | Student selectStudentWithAddress(int id);
method insertStudent (line 23) | void insertStudent(Student student);
method insertStudentWithMap (line 25) | void insertStudentWithMap(Map<String, Object> map);
method updateStudent (line 27) | void updateStudent(Student student);
method deleteStudent (line 29) | int deleteStudent(int id);
FILE: chapter03/src/main/java/com/mybatis3/mappers/TutorMapper.java
type TutorMapper (line 11) | public interface TutorMapper
method selectTutorWithCourses (line 14) | Tutor selectTutorWithCourses(int tutorId);
method selectTutorById (line 16) | Tutor selectTutorById(int tutorId);
FILE: chapter03/src/main/java/com/mybatis3/services/CourseService.java
class CourseService (line 15) | public class CourseService
method searchCourses (line 19) | public List<Course> searchCourses(Map<String, Object> map)
method searchCoursesByTutors (line 33) | public List<Course> searchCoursesByTutors(Map<String, Object> map) {
FILE: chapter03/src/main/java/com/mybatis3/services/StudentService.java
class StudentService (line 13) | public class StudentService
method findAllStudents (line 16) | public List<Student> findAllStudents()
method findStudentById (line 27) | public Student findStudentById(Integer id)
method findStudentWithAddressById (line 38) | public Student findStudentWithAddressById(int id) {
method createStudent (line 48) | public Student createStudent(Student student) {
method createStudentWithMap (line 66) | public void createStudentWithMap(Map<String, Object> studentDataMap) {
method updateStudent (line 83) | public Student updateStudent(Student student) {
method deleteStudent (line 101) | public boolean deleteStudent(int id) {
FILE: chapter03/src/main/java/com/mybatis3/services/TutorService.java
class TutorService (line 12) | public class TutorService
method findTutorById (line 17) | public Tutor findTutorById(int tutorId) {
FILE: chapter03/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
class PhoneTypeHandler (line 21) | public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
method setNonNullParameter (line 23) | @Override
method getNullableResult (line 29) | @Override
method getNullableResult (line 35) | @Override
method getNullableResult (line 41) | @Override
FILE: chapter03/src/main/java/com/mybatis3/util/MyBatisUtil.java
class MyBatisUtil (line 18) | public class MyBatisUtil
method getSqlSessionFactory (line 34) | public static SqlSessionFactory getSqlSessionFactory()
method getConnection (line 51) | public static Connection getConnection()
FILE: chapter03/src/main/resources/sql/create_tables.sql
type ADDRESSES (line 2) | CREATE TABLE ADDRESSES
type STUDENTS (line 13) | CREATE TABLE STUDENTS
type TUTORS (line 29) | CREATE TABLE TUTORS
type COURSES (line 46) | CREATE TABLE COURSES
type COURSE_ENROLLMENT (line 59) | CREATE TABLE COURSE_ENROLLMENT
FILE: chapter03/src/test/java/com/mybatis3/services/CourseServiceTest.java
class CourseServiceTest (line 16) | public class CourseServiceTest
method setup (line 20) | @BeforeClass
method teardown (line 27) | @AfterClass
method searchCourses (line 33) | @Test
method searchCoursesByTutors (line 48) | @Test
FILE: chapter03/src/test/java/com/mybatis3/services/StudentServiceTest.java
class StudentServiceTest (line 18) | public class StudentServiceTest
method setup (line 22) | @BeforeClass
method teardown (line 29) | @AfterClass
method testFindAllStudents (line 35) | @Test
method testFindStudentById (line 48) | @Test
method testFindStudentWithAddressById (line 56) | @Test
method testCreateStudent (line 64) | @Test
method testCreateStudentWithMap (line 80) | @Test
method testUpdateStudent (line 91) | @Test
method testDeleteStudent (line 106) | @Test
FILE: chapter03/src/test/java/com/mybatis3/services/TestDataPopulator.java
class TestDataPopulator (line 21) | public class TestDataPopulator
method main (line 25) | public static void main(String[] args) {
method initDatabase (line 29) | public static void initDatabase()
FILE: chapter03/src/test/java/com/mybatis3/services/TutorServiceTest.java
class TutorServiceTest (line 15) | public class TutorServiceTest
method setup (line 19) | @BeforeClass
method teardown (line 26) | @AfterClass
method testFindTutorById (line 33) | @Test
FILE: chapter04/src/main/java/com/mybatis3/domain/Address.java
class Address (line 9) | public class Address implements Serializable
method toString (line 20) | @Override
method Address (line 26) | public Address()
method Address (line 29) | public Address(Integer addrId)
method Address (line 33) | public Address(Integer addrId, String street, String city, String state,
method getAddrId (line 43) | public Integer getAddrId() {
method setAddrId (line 46) | public void setAddrId(Integer addrId) {
method getStreet (line 49) | public String getStreet()
method setStreet (line 53) | public void setStreet(String street)
method getCity (line 57) | public String getCity()
method setCity (line 61) | public void setCity(String city)
method getState (line 65) | public String getState()
method setState (line 69) | public void setState(String state)
method getZip (line 73) | public String getZip()
method setZip (line 77) | public void setZip(String zip)
method getCountry (line 81) | public String getCountry()
method setCountry (line 85) | public void setCountry(String country)
FILE: chapter04/src/main/java/com/mybatis3/domain/Course.java
class Course (line 12) | public class Course implements Serializable
method toString (line 24) | @Override
method getCourseId (line 30) | public Integer getCourseId()
method setCourseId (line 34) | public void setCourseId(Integer id)
method getName (line 38) | public String getName()
method setName (line 42) | public void setName(String name)
method getDescription (line 46) | public String getDescription()
method setDescription (line 50) | public void setDescription(String description)
method getStartDate (line 54) | public Date getStartDate()
method setStartDate (line 58) | public void setStartDate(Date startDate)
method getEndDate (line 62) | public Date getEndDate()
method setEndDate (line 66) | public void setEndDate(Date endDate)
method getStudents (line 70) | public List<Student> getStudents()
method setStudents (line 77) | public void setStudents(List<Student> students)
method getTutor (line 81) | public Tutor getTutor() {
method setTutor (line 84) | public void setTutor(Tutor tutor) {
FILE: chapter04/src/main/java/com/mybatis3/domain/PhoneNumber.java
class PhoneNumber (line 13) | public class PhoneNumber implements Serializable
method PhoneNumber (line 21) | public PhoneNumber() {
method PhoneNumber (line 24) | public PhoneNumber(String countryCode, String stateCode, String number) {
method PhoneNumber (line 31) | public PhoneNumber(String string) {
method getCountryCode (line 46) | public String getCountryCode() {
method setCountryCode (line 50) | public void setCountryCode(String countryCode) {
method getStateCode (line 54) | public String getStateCode() {
method setStateCode (line 58) | public void setStateCode(String stateCode) {
method getNumber (line 62) | public String getNumber() {
method setNumber (line 66) | public void setNumber(String number) {
method getAsString (line 70) | public String getAsString() {
FILE: chapter04/src/main/java/com/mybatis3/domain/Student.java
class Student (line 10) | public class Student implements Serializable
method toString (line 19) | @Override
method Student (line 24) | public Student()
method Student (line 27) | public Student(Integer id)
method getStudId (line 31) | public Integer getStudId()
method setStudId (line 35) | public void setStudId(Integer id)
method getName (line 39) | public String getName()
method setName (line 43) | public void setName(String name)
method getEmail (line 47) | public String getEmail()
method setEmail (line 51) | public void setEmail(String email)
method getAddress (line 55) | public Address getAddress() {
method setAddress (line 58) | public void setAddress(Address address) {
method getPhone (line 61) | public PhoneNumber getPhone() {
method setPhone (line 64) | public void setPhone(PhoneNumber phone) {
FILE: chapter04/src/main/java/com/mybatis3/domain/Tutor.java
class Tutor (line 10) | public class Tutor implements Serializable
method toString (line 20) | @Override
method Tutor (line 25) | public Tutor()
method Tutor (line 28) | public Tutor(Integer id)
method getTutorId (line 32) | public Integer getTutorId()
method setTutorId (line 36) | public void setTutorId(Integer id)
method getName (line 40) | public String getName()
method setName (line 44) | public void setName(String name)
method getEmail (line 48) | public String getEmail()
method setEmail (line 52) | public void setEmail(String email)
method getAddress (line 56) | public Address getAddress()
method setAddress (line 60) | public void setAddress(Address address)
method getCourses (line 64) | public List<Course> getCourses() {
method setCourses (line 67) | public void setCourses(List<Course> courses) {
FILE: chapter04/src/main/java/com/mybatis3/mappers/AddressMapper.java
type AddressMapper (line 14) | public interface AddressMapper
method selectAddressById (line 16) | @Select("select addr_id as addrId, street, city, state, zip, country f...
FILE: chapter04/src/main/java/com/mybatis3/mappers/StudentMapper.java
type StudentMapper (line 23) | public interface StudentMapper
method findAllStudents (line 26) | @Select("select * from students")
method findAllStudentsMap (line 35) | @Select("select stud_id as studId, name, email, addr_id as 'address.ad...
method findStudentById (line 38) | @Select("select stud_id as studId, name, email, addr_id as 'address.ad...
method findStudentMapById (line 41) | @Select("select stud_id as studId, name, email, addr_id as 'address.ad...
method selectStudentWithAddress (line 44) | @Select("select stud_id, name, email, a.addr_id, street, city, state, ...
method insertStudent (line 50) | @Insert("insert into students(name,email,addr_id, phone) values(#{name...
method insertStudentWithMap (line 54) | @Insert("insert into students(name,email,addr_id, phone) values(#{name...
method updateStudent (line 58) | @Update("update students set name=#{name}, email=#{email}, phone=#{pho...
method deleteStudent (line 61) | @Delete("delete from students where stud_id=#{studId}")
FILE: chapter04/src/main/java/com/mybatis3/mappers/TutorMapper.java
type TutorMapper (line 31) | public interface TutorMapper
method selectCoursesByTutorId (line 34) | @Select("select * from courses where tutor_id=#{tutorId}")
method selectTutorWithCoursesById (line 38) | @Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tu...
method findAllTutors (line 50) | @SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutors...
method findTutorById (line 53) | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorById...
method findTutorByNameAndEmail (line 56) | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNa...
method insertTutor (line 59) | @InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor")
method updateTutor (line 63) | @UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor")
method deleteTutor (line 66) | @DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor")
method selectTutorById (line 69) | @SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorBy...
FILE: chapter04/src/main/java/com/mybatis3/services/StudentService.java
class StudentService (line 14) | public class StudentService
method findAllStudents (line 18) | public List<Student> findAllStudents()
method findStudentById (line 29) | public Student findStudentById(Integer id)
method findStudentWithAddressById (line 41) | public Student findStudentWithAddressById(int id) {
method createStudent (line 51) | public Student createStudent(Student student) {
method createStudentWithMap (line 69) | public void createStudentWithMap(Map<String, Object> studentDataMap) {
method updateStudent (line 86) | public Student updateStudent(Student student) {
method deleteStudent (line 104) | public boolean deleteStudent(int id) {
method findStudentMapById (line 122) | public Map<String, Object> findStudentMapById(int id) {
method findAllStudentsMap (line 134) | public List<Map<String, Object>> findAllStudentsMap() {
FILE: chapter04/src/main/java/com/mybatis3/services/TutorService.java
class TutorService (line 20) | public class TutorService
method findAllTutors (line 22) | public List<Tutor> findAllTutors()
method findTutorById (line 33) | public Tutor findTutorById(int tutorId)
method findTutorByNameAndEmail (line 44) | public Tutor findTutorByNameAndEmail(String name, String email)
method createTutor (line 55) | public Tutor createTutor(Tutor tutor)
method updateTutor (line 68) | public Tutor updateTutor(Tutor tutor)
method deleteTutor (line 81) | public boolean deleteTutor(int tutorId)
method selectTutorById (line 96) | public Tutor selectTutorById(int tutorId)
method selectTutorWithCoursesById (line 107) | public Tutor selectTutorWithCoursesById(int tutorId) {
FILE: chapter04/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java
class TutorDynaSqlProvider (line 16) | public class TutorDynaSqlProvider
method findAllTutorsSql (line 19) | public String findAllTutorsSql()
method findTutorByIdSql (line 27) | public String findTutorByIdSql(final int tutorId)
method findTutorByNameAndEmailSql (line 43) | public String findTutorByNameAndEmailSql(Map<String, Object> map)
method insertTutor (line 56) | public String insertTutor(final Tutor tutor) {
method updateTutor (line 72) | public String updateTutor(final Tutor tutor)
method deleteTutor (line 89) | public String deleteTutor(int tutorId)
method selectTutorById (line 99) | public String selectTutorById()
FILE: chapter04/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
class PhoneTypeHandler (line 21) | public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
method setNonNullParameter (line 23) | @Override
method getNullableResult (line 29) | @Override
method getNullableResult (line 35) | @Override
method getNullableResult (line 41) | @Override
FILE: chapter04/src/main/java/com/mybatis3/util/MyBatisUtil.java
class MyBatisUtil (line 18) | public class MyBatisUtil
method getConnection (line 34) | public static Connection getConnection()
method getSqlSessionFactory (line 50) | public static SqlSessionFactory getSqlSessionFactory()
FILE: chapter04/src/main/resources/sql/create_tables.sql
type ADDRESSES (line 2) | CREATE TABLE ADDRESSES
type STUDENTS (line 13) | CREATE TABLE STUDENTS
type TUTORS (line 29) | CREATE TABLE TUTORS
type COURSES (line 46) | CREATE TABLE COURSES
type COURSE_ENROLLMENT (line 59) | CREATE TABLE COURSE_ENROLLMENT
FILE: chapter04/src/test/java/com/mybatis3/services/StudentServiceTest.java
class StudentServiceTest (line 16) | public class StudentServiceTest
method setup (line 21) | @BeforeClass
method teardown (line 27) | @AfterClass
method testFindAllStudents (line 32) | @Test
method testFindStudentById (line 42) | @Test
method testFindStudentWithAddressById (line 50) | @Test
method testCreateStudent (line 57) | @Test
method testCreateStudentWithMap (line 71) | @Test
method testUpdateStudent (line 81) | @Test
method testDeleteStudent (line 97) | @Test
method testFindStudentMapById (line 104) | @Test
method testFindAllStudentsMap (line 110) | @Test
FILE: chapter04/src/test/java/com/mybatis3/services/TestDataPopulator.java
class TestDataPopulator (line 20) | public class TestDataPopulator
method main (line 24) | public static void main(String[] args) {
method initDatabase (line 28) | public static void initDatabase()
FILE: chapter04/src/test/java/com/mybatis3/services/TutorServiceTest.java
class TutorServiceTest (line 13) | public class TutorServiceTest
method setup (line 18) | @BeforeClass
method teardown (line 24) | @AfterClass
method testFindAllTutors (line 29) | @Test
method testFindTutorById (line 39) | @Test
method testFindTutorByNameAndEmail (line 46) | @Test
method testCreateTutor (line 53) | @Test
method testUpdateTutor (line 63) | @Test
method testDeleteTutor (line 75) | @Test
method testSelectTutorById (line 81) | @Test
method testSelectTutorWithCoursesById (line 88) | @Test
FILE: chapter05/src/main/java/com/mybatis3/config/AppConfig.java
class AppConfig (line 16) | @Configuration
FILE: chapter05/src/main/java/com/mybatis3/domain/Address.java
class Address (line 9) | public class Address implements Serializable
method toString (line 20) | @Override
method Address (line 26) | public Address()
method Address (line 29) | public Address(Integer addrId)
method Address (line 33) | public Address(Integer addrId, String street, String city, String state,
method getAddrId (line 43) | public Integer getAddrId() {
method setAddrId (line 46) | public void setAddrId(Integer addrId) {
method getStreet (line 49) | public String getStreet()
method setStreet (line 53) | public void setStreet(String street)
method getCity (line 57) | public String getCity()
method setCity (line 61) | public void setCity(String city)
method getState (line 65) | public String getState()
method setState (line 69) | public void setState(String state)
method getZip (line 73) | public String getZip()
method setZip (line 77) | public void setZip(String zip)
method getCountry (line 81) | public String getCountry()
method setCountry (line 85) | public void setCountry(String country)
FILE: chapter05/src/main/java/com/mybatis3/domain/Course.java
class Course (line 12) | public class Course implements Serializable
method toString (line 24) | @Override
method getCourseId (line 30) | public Integer getCourseId()
method setCourseId (line 34) | public void setCourseId(Integer id)
method getName (line 38) | public String getName()
method setName (line 42) | public void setName(String name)
method getDescription (line 46) | public String getDescription()
method setDescription (line 50) | public void setDescription(String description)
method getStartDate (line 54) | public Date getStartDate()
method setStartDate (line 58) | public void setStartDate(Date startDate)
method getEndDate (line 62) | public Date getEndDate()
method setEndDate (line 66) | public void setEndDate(Date endDate)
method getStudents (line 70) | public List<Student> getStudents()
method setStudents (line 77) | public void setStudents(List<Student> students)
method getTutor (line 81) | public Tutor getTutor() {
method setTutor (line 84) | public void setTutor(Tutor tutor) {
FILE: chapter05/src/main/java/com/mybatis3/domain/PhoneNumber.java
class PhoneNumber (line 13) | public class PhoneNumber implements Serializable
method PhoneNumber (line 21) | public PhoneNumber() {
method PhoneNumber (line 24) | public PhoneNumber(String countryCode, String stateCode, String number) {
method PhoneNumber (line 31) | public PhoneNumber(String string) {
method getCountryCode (line 46) | public String getCountryCode() {
method setCountryCode (line 50) | public void setCountryCode(String countryCode) {
method getStateCode (line 54) | public String getStateCode() {
method setStateCode (line 58) | public void setStateCode(String stateCode) {
method getNumber (line 62) | public String getNumber() {
method setNumber (line 66) | public void setNumber(String number) {
method getAsString (line 70) | public String getAsString() {
FILE: chapter05/src/main/java/com/mybatis3/domain/Student.java
class Student (line 10) | public class Student implements Serializable
method toString (line 19) | @Override
method Student (line 24) | public Student()
method Student (line 27) | public Student(Integer id)
method getStudId (line 31) | public Integer getStudId()
method setStudId (line 35) | public void setStudId(Integer id)
method getName (line 39) | public String getName()
method setName (line 43) | public void setName(String name)
method getEmail (line 47) | public String getEmail()
method setEmail (line 51) | public void setEmail(String email)
method getAddress (line 55) | public Address getAddress() {
method setAddress (line 58) | public void setAddress(Address address) {
method getPhone (line 61) | public PhoneNumber getPhone() {
method setPhone (line 64) | public void setPhone(PhoneNumber phone) {
FILE: chapter05/src/main/java/com/mybatis3/domain/Tutor.java
class Tutor (line 10) | public class Tutor implements Serializable
method toString (line 20) | @Override
method Tutor (line 25) | public Tutor()
method Tutor (line 28) | public Tutor(Integer id)
method getTutorId (line 32) | public Integer getTutorId()
method setTutorId (line 36) | public void setTutorId(Integer id)
method getName (line 40) | public String getName()
method setName (line 44) | public void setName(String name)
method getEmail (line 48) | public String getEmail()
method setEmail (line 52) | public void setEmail(String email)
method getAddress (line 56) | public Address getAddress()
method setAddress (line 60) | public void setAddress(Address address)
method getCourses (line 64) | public List<Course> getCourses() {
method setCourses (line 67) | public void setCourses(List<Course> courses) {
FILE: chapter05/src/main/java/com/mybatis3/mappers/AddressMapper.java
type AddressMapper (line 15) | public interface AddressMapper
method selectAddressById (line 17) | @Select("select addr_id as addrId, street, city, state, zip, country f...
method insertAddress (line 20) | @Insert("insert into addresses(street, city, state, zip, country) valu...
FILE: chapter05/src/main/java/com/mybatis3/mappers/StudentMapper.java
type StudentMapper (line 23) | public interface StudentMapper
method findAllStudents (line 26) | @Select("select * from students")
method findAllStudentsMap (line 35) | @Select("select stud_id as studId, name, email, addr_id as 'address.ad...
method findStudentById (line 38) | @Select("select stud_id as studId, name, email, addr_id as 'address.ad...
method findStudentMapById (line 41) | @Select("select stud_id as studId, name, email, addr_id as 'address.ad...
method selectStudentWithAddress (line 44) | @Select("select stud_id, name, email, a.addr_id, street, city, state, ...
method insertStudent (line 50) | @Insert("insert into students(name,email,addr_id, phone) values(#{name...
method insertStudentWithMap (line 54) | @Insert("insert into students(name,email,addr_id, phone) values(#{name...
method updateStudent (line 58) | @Update("update students set name=#{name}, email=#{email}, phone=#{pho...
method deleteStudent (line 61) | @Delete("delete from students where stud_id=#{studId}")
FILE: chapter05/src/main/java/com/mybatis3/mappers/TutorMapper.java
type TutorMapper (line 31) | public interface TutorMapper
method selectCoursesByTutorId (line 34) | @Select("select * from courses where tutor_id=#{tutorId}")
method selectTutorWithCoursesById (line 38) | @Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tu...
method findAllTutors (line 50) | @SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutors...
method findTutorById (line 53) | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorById...
method findTutorByNameAndEmail (line 56) | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNa...
method insertTutor (line 59) | @InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor")
method updateTutor (line 63) | @UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor")
method deleteTutor (line 66) | @DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor")
method selectTutorById (line 69) | @SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorBy...
FILE: chapter05/src/main/java/com/mybatis3/services/StudentService.java
class StudentService (line 18) | @Service
method findAllStudents (line 30) | public List<Student> findAllStudents() {
method findStudentById (line 34) | public Student findStudentById(Integer id) {
method findStudentWithAddressById (line 39) | public Student findStudentWithAddressById(int id) {
method createStudent (line 43) | public Student createStudent(Student student) {
method createStudentWithMap (line 55) | public void createStudentWithMap(Map<String, Object> studentDataMap) {
method updateStudent (line 59) | public Student updateStudent(Student student) {
method deleteStudent (line 64) | public boolean deleteStudent(int id) {
method findStudentMapById (line 69) | public Map<String, Object> findStudentMapById(int id) {
method findAllStudentsMap (line 73) | public List<Map<String, Object>> findAllStudentsMap() {
FILE: chapter05/src/main/java/com/mybatis3/services/TutorService.java
class TutorService (line 21) | @Service
method getTutorMapper (line 28) | private TutorMapper getTutorMapper(){
method findAllTutors (line 31) | public List<Tutor> findAllTutors() {
method findTutorById (line 35) | public Tutor findTutorById(int tutorId) {
method findTutorByNameAndEmail (line 39) | public Tutor findTutorByNameAndEmail(String name, String email) {
method createTutor (line 43) | public Tutor createTutor(Tutor tutor) {
method updateTutor (line 48) | public Tutor updateTutor(Tutor tutor) {
method deleteTutor (line 53) | public boolean deleteTutor(int tutorId) {
method selectTutorById (line 60) | public Tutor selectTutorById(int tutorId) {
method selectTutorWithCoursesById (line 64) | public Tutor selectTutorWithCoursesById(int tutorId) {
FILE: chapter05/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java
class TutorDynaSqlProvider (line 15) | public class TutorDynaSqlProvider
method findAllTutorsSql (line 18) | public String findAllTutorsSql()
method findTutorByIdSql (line 26) | public String findTutorByIdSql(final int tutorId)
method findTutorByNameAndEmailSql (line 36) | public String findTutorByNameAndEmailSql(Map<String, Object> map)
method insertTutor (line 48) | public String insertTutor(final Tutor tutor) {
method updateTutor (line 62) | public String updateTutor(final Tutor tutor)
method deleteTutor (line 78) | public String deleteTutor(int tutorId)
method selectTutorById (line 86) | public String selectTutorById()
FILE: chapter05/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java
class PhoneTypeHandler (line 21) | public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{
method setNonNullParameter (line 23) | @Override
method getNullableResult (line 29) | @Override
method getNullableResult (line 35) | @Override
method getNullableResult (line 41) | @Override
FILE: chapter05/src/main/java/com/mybatis3/util/MyBatisUtil.java
class MyBatisUtil (line 18) | public class MyBatisUtil
method getConnection (line 34) | public static Connection getConnection()
method getSqlSessionFactory (line 50) | public static SqlSessionFactory getSqlSessionFactory()
FILE: chapter05/src/main/resources/sql/create_tables.sql
type ADDRESSES (line 2) | CREATE TABLE ADDRESSES
type STUDENTS (line 13) | CREATE TABLE STUDENTS
type TUTORS (line 29) | CREATE TABLE TUTORS
type COURSES (line 46) | CREATE TABLE COURSES
type COURSE_ENROLLMENT (line 59) | CREATE TABLE COURSE_ENROLLMENT
FILE: chapter05/src/test/java/com/mybatis3/services/StudentServiceTest.java
class StudentServiceTest (line 21) | @RunWith(SpringJUnit4ClassRunner.class)
method setup (line 28) | @BeforeClass
method testFindAllStudents (line 33) | @Test
method testFindStudentById (line 43) | @Test
method testFindStudentWithAddressById (line 51) | @Test
method testCreateStudent (line 58) | @Test
method testCreateStudentForException (line 81) | @Test(expected=DataAccessException.class)
method testCreateStudentWithMap (line 100) | @Test
method testUpdateStudent (line 110) | @Test
method testDeleteStudent (line 126) | @Test
method testFindStudentMapById (line 133) | @Test
method testFindAllStudentsMap (line 139) | @Test
FILE: chapter05/src/test/java/com/mybatis3/services/TestDataPopulator.java
class TestDataPopulator (line 20) | public class TestDataPopulator
method main (line 24) | public static void main(String[] args) {
method initDatabase (line 28) | public static void initDatabase()
FILE: chapter05/src/test/java/com/mybatis3/services/TutorServiceTest.java
class TutorServiceTest (line 16) | @RunWith(SpringJUnit4ClassRunner.class)
method setup (line 23) | @BeforeClass
method testFindAllTutors (line 29) | @Test
method testFindTutorById (line 39) | @Test
method testFindTutorByNameAndEmail (line 46) | @Test
method testCreateTutor (line 53) | @Test
method testUpdateTutor (line 62) | @Test
method testDeleteTutor (line 74) | @Test
method testSelectTutorById (line 80) | @Test
method testSelectTutorWithCoursesById (line 87) | @Test
Condensed preview — 126 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (214K chars).
[
{
"path": ".gitignore",
"chars": 108,
"preview": "\n.project\n.classpath\n.settings\n.springBeans\n\ntarget\nbin\nbuild\n\n*.class\n\n# Package Files #\n*.jar\n*.war\n*.ear\n"
},
{
"path": "README.md",
"chars": 215,
"preview": "Java Persistence with MyBatis3 Book Sample Code\n========================\n1. Getting started with MyBatis\n2. Bootstrappin"
},
{
"path": "chapter01/README.txt",
"chars": 437,
"preview": "Chapter 1: Getting started with MyBatis\r\n=======================================\r\nThis module, chapter01, is a maven bas"
},
{
"path": "chapter01/pom.xml",
"chars": 2429,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/"
},
{
"path": "chapter01/src/main/java/com/mybatis3/domain/Student.java",
"chars": 1091,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.util.Date;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Student\r\n{\r\n\tpri"
},
{
"path": "chapter01/src/main/java/com/mybatis3/mappers/StudentMapper.java",
"chars": 331,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\n\r\nimport com.mybatis3.domain.Student;\r\n\r\n\r\n/**\r\n * @author Siva"
},
{
"path": "chapter01/src/main/java/com/mybatis3/services/JdbcStudentService.java",
"chars": 3920,
"preview": "package com.mybatis3.services;\r\n\r\nimport java.sql.Connection;\r\nimport java.sql.DriverManager;\r\nimport java.sql.PreparedS"
},
{
"path": "chapter01/src/main/java/com/mybatis3/services/StudentService.java",
"chars": 1755,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\n\nimport org.apache.ibatis.session.SqlSession;\nimport org.slf4j.Lo"
},
{
"path": "chapter01/src/main/java/com/mybatis3/util/MyBatisSqlSessionFactory.java",
"chars": 2028,
"preview": "package com.mybatis3.util;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.sql.Connection;\r\nimp"
},
{
"path": "chapter01/src/main/resources/application.properties",
"chars": 212,
"preview": "\r\n\r\n################### DataSource Configuration ##########################\r\n\r\njdbc.driverClassName=com.mysql.jdbc.Drive"
},
{
"path": "chapter01/src/main/resources/com/mybatis3/mappers/StudentMapper.xml",
"chars": 1091,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter01/src/main/resources/log4j.properties",
"chars": 251,
"preview": "log4j.rootLogger=INFO, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=or"
},
{
"path": "chapter01/src/main/resources/mybatis-config.xml",
"chars": 912,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE configuration\r\n PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\"\r\n \"http"
},
{
"path": "chapter01/src/main/resources/sql/create_tables.sql",
"chars": 2208,
"preview": "\r\nCREATE TABLE ADDRESSES \r\n(\r\n ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,\r\n STREET VARCHAR(50) NOT NULL,\r\n CITY VARCHAR"
},
{
"path": "chapter01/src/main/resources/sql/drop_tables.sql",
"chars": 204,
"preview": "\r\nDROP TABLE IF EXISTS USER_PICS;\r\nDROP TABLE IF EXISTS COURSE_ENROLLMENT;\r\nDROP TABLE IF EXISTS COURSES;\r\nDROP TABLE IF"
},
{
"path": "chapter01/src/main/resources/sql/sample_data.sql",
"chars": 1352,
"preview": "\n\n--Sample data for table ADDRESSES\n\nINSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES \n (1,'4891 Pac"
},
{
"path": "chapter01/src/test/java/com/mybatis3/services/StudentServiceTest.java",
"chars": 1955,
"preview": "package com.mybatis3.services;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.junit.AfterClass;\nimport stati"
},
{
"path": "chapter01/src/test/java/com/mybatis3/services/TestDataPopulator.java",
"chars": 1402,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.io.Reader;\r\nimport java.sql.Connection;\r\n\r\nimport org.apach"
},
{
"path": "chapter01/src/test/resources/log4j.properties",
"chars": 252,
"preview": "log4j.rootLogger=DEBUG, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=o"
},
{
"path": "chapter02/README.txt",
"chars": 665,
"preview": "Chapter 2: Bootstrapping MyBatis\r\n=======================================\r\nThis module, chapter02, is a maven based java"
},
{
"path": "chapter02/pom.xml",
"chars": 2293,
"preview": "<?xml version=\"1.0\"?>\n<project\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n\thttp://maven.apache.org/xsd/mave"
},
{
"path": "chapter02/src/main/java/com/mybatis3/domain/PhoneNumber.java",
"chars": 1267,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.domain;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class PhoneNumber \r\n{\r\n\tprivate S"
},
{
"path": "chapter02/src/main/java/com/mybatis3/domain/Student.java",
"chars": 1144,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.util.Date;\r\n\r\nimport org.apache.ibatis.type.Alias;\r\n\r\n\r\n/**\r\n * @author Siva"
},
{
"path": "chapter02/src/main/java/com/mybatis3/mappers/StudentMapper.java",
"chars": 331,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\n\r\nimport com.mybatis3.domain.Student;\r\n\r\n\r\n/**\r\n * @author Siva"
},
{
"path": "chapter02/src/main/java/com/mybatis3/services/StudentService.java",
"chars": 1845,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\n\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.i"
},
{
"path": "chapter02/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java",
"chars": 1134,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.typehandlers;\r\n\r\nimport java.sql.CallableStatement;\r\nimport java.sql.PreparedStateme"
},
{
"path": "chapter02/src/main/java/com/mybatis3/util/DataSourceFactory.java",
"chars": 1418,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.util;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.util."
},
{
"path": "chapter02/src/main/java/com/mybatis3/util/MyBatisUtil.java",
"chars": 2085,
"preview": "package com.mybatis3.util;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\n\r\nimport javax.sql.DataSource;\r\n"
},
{
"path": "chapter02/src/main/resources/application.properties",
"chars": 212,
"preview": "\r\n\r\n################### DataSource Configuration ##########################\r\n\r\njdbc.driverClassName=com.mysql.jdbc.Drive"
},
{
"path": "chapter02/src/main/resources/com/mybatis3/mappers/StudentMapper.xml",
"chars": 1118,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter02/src/main/resources/full-mybatis-config.xml",
"chars": 2492,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE configuration\r\n PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\"\r\n \"http"
},
{
"path": "chapter02/src/main/resources/log4j.properties",
"chars": 251,
"preview": "log4j.rootLogger=INFO, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=or"
},
{
"path": "chapter02/src/main/resources/mybatis-config.xml",
"chars": 1859,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE configuration\r\n PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\"\r\n \"http"
},
{
"path": "chapter02/src/main/resources/sql/create_tables.sql",
"chars": 2208,
"preview": "\r\nCREATE TABLE ADDRESSES \r\n(\r\n ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,\r\n STREET VARCHAR(50) NOT NULL,\r\n CITY VARCHAR"
},
{
"path": "chapter02/src/main/resources/sql/drop_tables.sql",
"chars": 204,
"preview": "\r\nDROP TABLE IF EXISTS USER_PICS;\r\nDROP TABLE IF EXISTS COURSE_ENROLLMENT;\r\nDROP TABLE IF EXISTS COURSES;\r\nDROP TABLE IF"
},
{
"path": "chapter02/src/main/resources/sql/sample_data.sql",
"chars": 1352,
"preview": "\n\n--Sample data for table ADDRESSES\n\nINSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES \n (1,'4891 Pac"
},
{
"path": "chapter02/src/test/java/com/mybatis3/services/StudentServiceTest.java",
"chars": 2350,
"preview": "package com.mybatis3.services;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNul"
},
{
"path": "chapter02/src/test/java/com/mybatis3/services/TestDataPopulator.java",
"chars": 1406,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.io.Reader;\r\nimport java.sql.Connection;\r\n\r\nimport org.apach"
},
{
"path": "chapter03/README.txt",
"chars": 546,
"preview": "Chapter 3: SQL Mappers using XML\r\n=================================\r\nThis chapter describes mapping SQL statements and q"
},
{
"path": "chapter03/pom.xml",
"chars": 2293,
"preview": "<?xml version=\"1.0\"?>\n<project\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n\thttp://maven.apache.org/xsd/mave"
},
{
"path": "chapter03/src/main/java/com/mybatis3/domain/Address.java",
"chars": 1633,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Address impl"
},
{
"path": "chapter03/src/main/java/com/mybatis3/domain/Course.java",
"chars": 1732,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.ArrayList;\r\nimport java.util.Date;\r\nimpor"
},
{
"path": "chapter03/src/main/java/com/mybatis3/domain/PhoneNumber.java",
"chars": 1381,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic c"
},
{
"path": "chapter03/src/main/java/com/mybatis3/domain/Student.java",
"chars": 1244,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Student im"
},
{
"path": "chapter03/src/main/java/com/mybatis3/domain/Tutor.java",
"chars": 1261,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.List;\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\np"
},
{
"path": "chapter03/src/main/java/com/mybatis3/mappers/AddressMapper.java",
"chars": 184,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport com.mybatis3.domain.Address;\r\n\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic interf"
},
{
"path": "chapter03/src/main/java/com/mybatis3/mappers/CourseMapper.java",
"chars": 368,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport com.mybatis3.domain.Course;\r\n\r\n"
},
{
"path": "chapter03/src/main/java/com/mybatis3/mappers/StudentMapper.java",
"chars": 493,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport com.mybatis3.domain.Student;\r\n\r"
},
{
"path": "chapter03/src/main/java/com/mybatis3/mappers/TutorMapper.java",
"chars": 232,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport com.mybatis3.domain.Tutor;\r\n\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic interfac"
},
{
"path": "chapter03/src/main/java/com/mybatis3/services/CourseService.java",
"chars": 1055,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.ibatis.session.SqlSessio"
},
{
"path": "chapter03/src/main/java/com/mybatis3/services/StudentService.java",
"chars": 3001,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.ibatis.session.SqlSessio"
},
{
"path": "chapter03/src/main/java/com/mybatis3/services/TutorService.java",
"chars": 678,
"preview": "package com.mybatis3.services;\n\nimport org.apache.ibatis.session.SqlSession;\nimport org.slf4j.Logger;\nimport org.slf4j.L"
},
{
"path": "chapter03/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java",
"chars": 1134,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.typehandlers;\r\n\r\nimport java.sql.CallableStatement;\r\nimport java.sql.PreparedStateme"
},
{
"path": "chapter03/src/main/java/com/mybatis3/util/MyBatisUtil.java",
"chars": 1859,
"preview": "package com.mybatis3.util;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.sql.Connection;\r\nimp"
},
{
"path": "chapter03/src/main/resources/application.properties",
"chars": 220,
"preview": "\r\n\r\n################### DataSource Configuration ##########################\r\n\r\njdbc.driverClassName=com.mysql.jdbc.Drive"
},
{
"path": "chapter03/src/main/resources/com/mybatis3/mappers/AddressMapper.xml",
"chars": 726,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter03/src/main/resources/com/mybatis3/mappers/CourseMapper.xml",
"chars": 1588,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter03/src/main/resources/com/mybatis3/mappers/StudentMapper.xml",
"chars": 3417,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter03/src/main/resources/com/mybatis3/mappers/TutorMapper.xml",
"chars": 1865,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter03/src/main/resources/log4j.properties",
"chars": 251,
"preview": "log4j.rootLogger=INFO, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=or"
},
{
"path": "chapter03/src/main/resources/mybatis-config.xml",
"chars": 938,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE configuration\r\n PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\"\r\n \"http"
},
{
"path": "chapter03/src/main/resources/sql/create_tables.sql",
"chars": 2126,
"preview": "\r\nCREATE TABLE ADDRESSES \r\n(\r\n ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,\r\n STREET VARCHAR(50) NOT NULL,\r\n CITY VARCHAR"
},
{
"path": "chapter03/src/main/resources/sql/drop_tables.sql",
"chars": 204,
"preview": "\r\nDROP TABLE IF EXISTS USER_PICS;\r\nDROP TABLE IF EXISTS COURSE_ENROLLMENT;\r\nDROP TABLE IF EXISTS COURSES;\r\nDROP TABLE IF"
},
{
"path": "chapter03/src/main/resources/sql/sample_data.sql",
"chars": 1527,
"preview": "\n\n--Sample data for table ADDRESSES\n\nINSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES \n (1,'4891 Pac"
},
{
"path": "chapter03/src/test/java/com/mybatis3/services/CourseServiceTest.java",
"chars": 1490,
"preview": "package com.mybatis3.services;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java"
},
{
"path": "chapter03/src/test/java/com/mybatis3/services/StudentServiceTest.java",
"chars": 2622,
"preview": "package com.mybatis3.services;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.junit"
},
{
"path": "chapter03/src/test/java/com/mybatis3/services/TestDataPopulator.java",
"chars": 1379,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.io.Reader;\r\nimport java.sql.Connection;\r\n\r\nimport org.apach"
},
{
"path": "chapter03/src/test/java/com/mybatis3/services/TutorServiceTest.java",
"chars": 826,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\n\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org"
},
{
"path": "chapter04/README.txt",
"chars": 792,
"preview": "Chapter 4: SQL Mappers using Annotations\r\n========================================\r\nThis chapter describes mapping SQL s"
},
{
"path": "chapter04/pom.xml",
"chars": 2341,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "chapter04/src/main/java/com/mybatis3/domain/Address.java",
"chars": 1633,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Address impl"
},
{
"path": "chapter04/src/main/java/com/mybatis3/domain/Course.java",
"chars": 1732,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.ArrayList;\r\nimport java.util.Date;\r\nimpor"
},
{
"path": "chapter04/src/main/java/com/mybatis3/domain/PhoneNumber.java",
"chars": 1381,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic c"
},
{
"path": "chapter04/src/main/java/com/mybatis3/domain/Student.java",
"chars": 1244,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Student im"
},
{
"path": "chapter04/src/main/java/com/mybatis3/domain/Tutor.java",
"chars": 1261,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.List;\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\np"
},
{
"path": "chapter04/src/main/java/com/mybatis3/mappers/AddressMapper.java",
"chars": 350,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.mappers;\r\n\r\nimport org.apache.ibatis.annotations.Select;\r\n\r\nimport com.mybatis3.doma"
},
{
"path": "chapter04/src/main/java/com/mybatis3/mappers/StudentMapper.java",
"chars": 2362,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.ibatis.annotations.D"
},
{
"path": "chapter04/src/main/java/com/mybatis3/mappers/TutorMapper.java",
"chars": 2614,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\n\r\nimport org.apache.ibatis.annotations.DeletePro"
},
{
"path": "chapter04/src/main/java/com/mybatis3/services/StudentService.java",
"chars": 3782,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.ibatis.session.SqlSessio"
},
{
"path": "chapter04/src/main/java/com/mybatis3/services/TutorService.java",
"chars": 2854,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.util.List;\r\n\r\nimport org.apache.ibatis.session.SqlSession;\r"
},
{
"path": "chapter04/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java",
"chars": 2423,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.sqlproviders;\r\n\r\n\r\nimport java.util.Map;\r\n\r\nimport org.apache.ibatis.jdbc.SQL;\r\n\r\nim"
},
{
"path": "chapter04/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java",
"chars": 1139,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.typehandlers;\r\n\r\nimport java.sql.CallableStatement;\r\nimport java.sql.PreparedStateme"
},
{
"path": "chapter04/src/main/java/com/mybatis3/util/MyBatisUtil.java",
"chars": 1727,
"preview": "package com.mybatis3.util;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.sql.Connection;\r\nimp"
},
{
"path": "chapter04/src/main/resources/application.properties",
"chars": 212,
"preview": "\r\n\r\n################### DataSource Configuration ##########################\r\n\r\njdbc.driverClassName=com.mysql.jdbc.Drive"
},
{
"path": "chapter04/src/main/resources/com/mybatis3/mappers/StudentMapper.xml",
"chars": 851,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter04/src/main/resources/com/mybatis3/mappers/TutorMapper.xml",
"chars": 1270,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter04/src/main/resources/log4j.properties",
"chars": 251,
"preview": "log4j.rootLogger=INFO, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=or"
},
{
"path": "chapter04/src/main/resources/mybatis-config.xml",
"chars": 1000,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE configuration\r\n PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\"\r\n \"http"
},
{
"path": "chapter04/src/main/resources/sql/create_tables.sql",
"chars": 2126,
"preview": "\r\nCREATE TABLE ADDRESSES \r\n(\r\n ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,\r\n STREET VARCHAR(50) NOT NULL,\r\n CITY VARCHAR"
},
{
"path": "chapter04/src/main/resources/sql/drop_tables.sql",
"chars": 204,
"preview": "\r\nDROP TABLE IF EXISTS USER_PICS;\r\nDROP TABLE IF EXISTS COURSE_ENROLLMENT;\r\nDROP TABLE IF EXISTS COURSES;\r\nDROP TABLE IF"
},
{
"path": "chapter04/src/main/resources/sql/sample_data.sql",
"chars": 1548,
"preview": "\n\n--Sample data for table ADDRESSES\n\nINSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES \n (1,'4891 Pac"
},
{
"path": "chapter04/src/test/java/com/mybatis3/services/StudentServiceTest.java",
"chars": 3468,
"preview": "package com.mybatis3.services;\r\n\r\nimport static org.junit.Assert.*;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.List;"
},
{
"path": "chapter04/src/test/java/com/mybatis3/services/TestDataPopulator.java",
"chars": 1376,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.io.Reader;\r\nimport java.sql.Connection;\r\n\r\nimport org.apach"
},
{
"path": "chapter04/src/test/java/com/mybatis3/services/TutorServiceTest.java",
"chars": 2112,
"preview": "package com.mybatis3.services;\r\n\r\nimport static org.junit.Assert.*;\r\n\r\nimport java.util.List;\r\n\r\nimport org.junit.AfterC"
},
{
"path": "chapter05/README.txt",
"chars": 721,
"preview": "Chapter 5: Integration with Spring\r\nThis chapter explains how to integration MyBatis with Spring framework.\r\nTopics cove"
},
{
"path": "chapter05/pom.xml",
"chars": 4289,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "chapter05/src/main/java/com/mybatis3/config/AppConfig.java",
"chars": 960,
"preview": "package com.mybatis3.config;\r\n\r\nimport org.mybatis.spring.annotation.MapperScan;\r\nimport org.springframework.context.ann"
},
{
"path": "chapter05/src/main/java/com/mybatis3/domain/Address.java",
"chars": 1633,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Address impl"
},
{
"path": "chapter05/src/main/java/com/mybatis3/domain/Course.java",
"chars": 1732,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.ArrayList;\r\nimport java.util.Date;\r\nimpor"
},
{
"path": "chapter05/src/main/java/com/mybatis3/domain/PhoneNumber.java",
"chars": 1381,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic c"
},
{
"path": "chapter05/src/main/java/com/mybatis3/domain/Student.java",
"chars": 1244,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\n\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\npublic class Student im"
},
{
"path": "chapter05/src/main/java/com/mybatis3/domain/Tutor.java",
"chars": 1261,
"preview": "package com.mybatis3.domain;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.List;\r\n\r\n/**\r\n * @author Siva\r\n *\r\n */\r\np"
},
{
"path": "chapter05/src/main/java/com/mybatis3/mappers/AddressMapper.java",
"chars": 559,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.mappers;\r\n\r\nimport org.apache.ibatis.annotations.Insert;\r\nimport org.apache.ibatis.a"
},
{
"path": "chapter05/src/main/java/com/mybatis3/mappers/StudentMapper.java",
"chars": 2362,
"preview": "package com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.ibatis.annotations.D"
},
{
"path": "chapter05/src/main/java/com/mybatis3/mappers/TutorMapper.java",
"chars": 2614,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.mappers;\r\n\r\nimport java.util.List;\r\n\r\nimport org.apache.ibatis.annotations.DeletePro"
},
{
"path": "chapter05/src/main/java/com/mybatis3/services/StudentService.java",
"chars": 1966,
"preview": "package com.mybatis3.services;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j."
},
{
"path": "chapter05/src/main/java/com/mybatis3/services/TutorService.java",
"chars": 1567,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.util.List;\r\n\r\nimport org.apache.ibatis.session.SqlSession;\r"
},
{
"path": "chapter05/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java",
"chars": 2279,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.sqlproviders;\r\n\r\nimport java.util.Map;\r\n\r\nimport org.apache.ibatis.jdbc.SQL;\r\n\r\nimpo"
},
{
"path": "chapter05/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java",
"chars": 1139,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.typehandlers;\r\n\r\nimport java.sql.CallableStatement;\r\nimport java.sql.PreparedStateme"
},
{
"path": "chapter05/src/main/java/com/mybatis3/util/MyBatisUtil.java",
"chars": 1727,
"preview": "package com.mybatis3.util;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.sql.Connection;\r\nimp"
},
{
"path": "chapter05/src/main/resources/application.properties",
"chars": 214,
"preview": "\r\n\r\n################### DataSource Configuration ##########################\r\n\r\njdbc.driverClassName=com.mysql.jdbc.Drive"
},
{
"path": "chapter05/src/main/resources/applicationContext.xml",
"chars": 2550,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\r\n\txmlns:xsi=\"http://w"
},
{
"path": "chapter05/src/main/resources/com/mybatis3/mappers/StudentMapper.xml",
"chars": 851,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter05/src/main/resources/com/mybatis3/mappers/TutorMapper.xml",
"chars": 1270,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<!DOCTYPE mapper\r\n PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\r\n \"http://myba"
},
{
"path": "chapter05/src/main/resources/log4j.properties",
"chars": 251,
"preview": "log4j.rootLogger=INFO, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=or"
},
{
"path": "chapter05/src/main/resources/sql/create_tables.sql",
"chars": 2126,
"preview": "\r\nCREATE TABLE ADDRESSES \r\n(\r\n ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,\r\n STREET VARCHAR(50) NOT NULL,\r\n CITY VARCHAR"
},
{
"path": "chapter05/src/main/resources/sql/drop_tables.sql",
"chars": 204,
"preview": "\r\nDROP TABLE IF EXISTS USER_PICS;\r\nDROP TABLE IF EXISTS COURSE_ENROLLMENT;\r\nDROP TABLE IF EXISTS COURSES;\r\nDROP TABLE IF"
},
{
"path": "chapter05/src/main/resources/sql/sample_data.sql",
"chars": 1548,
"preview": "\n\n--Sample data for table ADDRESSES\n\nINSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES \n (1,'4891 Pac"
},
{
"path": "chapter05/src/test/java/com/mybatis3/services/StudentServiceTest.java",
"chars": 4682,
"preview": "package com.mybatis3.services;\r\n\r\nimport static org.junit.Assert.*;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.List;"
},
{
"path": "chapter05/src/test/java/com/mybatis3/services/TestDataPopulator.java",
"chars": 1376,
"preview": "/**\r\n * \r\n */\r\npackage com.mybatis3.services;\r\n\r\nimport java.io.Reader;\r\nimport java.sql.Connection;\r\n\r\nimport org.apach"
},
{
"path": "chapter05/src/test/java/com/mybatis3/services/TutorServiceTest.java",
"chars": 2276,
"preview": "package com.mybatis3.services;\r\n\r\nimport static org.junit.Assert.*;\r\n\r\nimport java.util.List;\r\n\r\nimport org.junit.Before"
},
{
"path": "elearning/README.txt",
"chars": 88,
"preview": "This module demonstrate developing a simple web app using MyBatis persistence framework."
},
{
"path": "elearning/pom.xml",
"chars": 7527,
"preview": "<?xml version=\"1.0\"?>\n<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4"
},
{
"path": "elearning/src/main/resources/log4j.properties",
"chars": 570,
"preview": "log4j.rootLogger=INFO, stdout\r\n\r\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.stdout.layout=or"
},
{
"path": "elearning/src/main/webapp/WEB-INF/web.xml",
"chars": 215,
"preview": "<!DOCTYPE web-app PUBLIC\n \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n \"http://java.sun.com/dtd/web-app_2_3"
},
{
"path": "elearning/src/main/webapp/index.jsp",
"chars": 52,
"preview": "<html>\n<body>\n<h2>Hello World!</h2>\n</body>\n</html>\n"
}
]
About this extraction
This page contains the full source code of the sivaprasadreddy/Java-Persistence-with-MyBatis3 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 126 files (177.1 KB), approximately 51.9k tokens, and a symbol index with 572 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.