├── .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
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .project
3 | .classpath
4 | .settings
5 | .springBeans
6 |
7 | target
8 | bin
9 | build
10 |
11 | *.class
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Java Persistence with MyBatis3 Book Sample Code
2 | ========================
3 | 1. Getting started with MyBatis
4 | 2. Bootstrapping MyBatis
5 | 3. SQL Mappers using XML
6 | 4. SQL Mappers using Annotations
7 | 5. Integration with Spring
8 |
--------------------------------------------------------------------------------
/chapter01/README.txt:
--------------------------------------------------------------------------------
1 | Chapter 1: Getting started with MyBatis
2 | =======================================
3 | This module, chapter01, is a maven based java project with MyBatis configured.
4 |
5 | How to Run:
6 | 1. Create MySQL Database tables using scripts in src/main/resources/sql folder.
7 | 2. Configure Database Connection properties like hostname, username and password in src/main/resources/application.properties file.
8 | 3. Run StudentServiceTest JUnit Test class.
--------------------------------------------------------------------------------
/chapter01/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.mybatis3
8 | chapter01
9 | 0.0.1
10 | jar
11 |
12 | chapter01
13 | http://www.mybatis.org
14 | MyBatis Book Chapter 01
15 |
16 |
17 | UTF-8
18 | 1.6
19 | 4.11
20 | 1.7.5
21 | 1.2.17
22 | 3.2.2
23 | 5.1.21
24 | 2.3.2
25 |
26 |
27 |
28 | ${project.artifactId}
29 |
30 |
31 | org.apache.maven.plugins
32 | maven-compiler-plugin
33 | ${maven.compiler.plugin}
34 |
35 | ${java.version}
36 | ${java.version}
37 | ${project.build.sourceEncoding}
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | junit
48 | junit
49 | ${junit.version}
50 | test
51 |
52 |
53 |
54 | org.mybatis
55 | mybatis
56 | ${mybatis.version}
57 |
58 |
59 |
60 | org.slf4j
61 | slf4j-api
62 | ${slf4j.version}
63 |
64 |
65 |
66 | org.slf4j
67 | slf4j-log4j12
68 | ${slf4j.version}
69 | runtime
70 |
71 |
72 |
73 | log4j
74 | log4j
75 | ${log4j.version}
76 | runtime
77 |
78 |
79 |
80 | mysql
81 | mysql-connector-java
82 | ${mysql.version}
83 | runtime
84 |
85 |
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/com/mybatis3/domain/Student.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.util.Date;
4 |
5 |
6 | /**
7 | * @author Siva
8 | *
9 | */
10 | public class Student
11 | {
12 | private Integer studId;
13 | private String name;
14 | private String email;
15 | private Date dob;
16 |
17 | public Student() {
18 |
19 | }
20 |
21 | public Student(Integer studId) {
22 | this.studId = studId;
23 | }
24 |
25 | public Student(Integer studId, String name, String email, Date dob) {
26 | this.studId = studId;
27 | this.name = name;
28 | this.email = email;
29 | this.dob = dob;
30 | }
31 |
32 | @Override
33 | public String toString() {
34 | return "Student [studId=" + studId + ", name=" + name + ", email="
35 | + email + ", dob=" + dob + "]";
36 | }
37 |
38 | public Integer getStudId() {
39 | return studId;
40 | }
41 | public void setStudId(Integer studId) {
42 | this.studId = studId;
43 | }
44 | public String getName() {
45 | return name;
46 | }
47 | public void setName(String name) {
48 | this.name = name;
49 | }
50 | public String getEmail() {
51 | return email;
52 | }
53 | public void setEmail(String email) {
54 | this.email = email;
55 | }
56 | public Date getDob() {
57 | return dob;
58 | }
59 | public void setDob(Date dob) {
60 | this.dob = dob;
61 | }
62 |
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/com/mybatis3/mappers/StudentMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import java.util.List;
4 |
5 | import com.mybatis3.domain.Student;
6 |
7 |
8 | /**
9 | * @author Siva
10 | *
11 | */
12 | public interface StudentMapper
13 | {
14 |
15 | List findAllStudents();
16 |
17 | Student findStudentById(Integer id);
18 |
19 | void insertStudent(Student student);
20 |
21 | void updateStudent(Student student);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/com/mybatis3/services/JdbcStudentService.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.sql.Connection;
4 | import java.sql.DriverManager;
5 | import java.sql.PreparedStatement;
6 | import java.sql.ResultSet;
7 | import java.sql.SQLException;
8 | import java.util.Date;
9 |
10 | import com.mybatis3.domain.Student;
11 |
12 |
13 | /**
14 | * @author Siva
15 | *
16 | */
17 |
18 | public class JdbcStudentService
19 | {
20 |
21 | private static final String DRIVER = "com.mysql.jdbc.Driver";
22 | private static final String URL = "jdbc:mysql://localhost:3306/elearning";
23 | private static final String USERNAME = "root";
24 | private static final String PASSWORD = "admin";
25 |
26 | public static void main(String[] args)
27 | {
28 |
29 | JdbcStudentService service = new JdbcStudentService();
30 |
31 | Student existingStudent = service.findStudentById(1);
32 | System.out.println(existingStudent);
33 |
34 |
35 | long ts = System.currentTimeMillis();//For creating unique student names
36 | Student newStudent = new Student(0,"student_"+ts,"student_"+ts+"@gmail.com",new Date());
37 | service.createStudent(newStudent);
38 | System.out.println(newStudent);
39 |
40 | int updateStudId = 3;
41 | Student updateStudent = service.findStudentById(updateStudId);
42 | ts = System.currentTimeMillis();//For creating unique student email
43 | updateStudent.setEmail("student_"+ts+"@gmail.com");
44 | service.updateStudent(updateStudent);
45 |
46 | }
47 |
48 | public Student findStudentById(int studId)
49 | {
50 | Student student = null;
51 | Connection conn = null;
52 | try
53 | {
54 | conn = getDatabaseConnection();
55 | String sql = "select * from students where stud_id=?";
56 | PreparedStatement pstmt = conn.prepareStatement(sql);
57 | pstmt.setInt(1, studId);
58 | ResultSet rs = pstmt.executeQuery();
59 | if(rs.next())
60 | {
61 | student = new Student();
62 | student.setStudId(rs.getInt("stud_id"));
63 | student.setName(rs.getString("name"));
64 | student.setEmail(rs.getString("email"));
65 | student.setDob(rs.getDate("dob"));
66 | }
67 |
68 | } catch (SQLException e)
69 | {
70 | throw new RuntimeException(e);
71 | }
72 | finally
73 | {
74 | if(conn!= null){
75 | try {
76 | conn.close();
77 | } catch (SQLException e){ }
78 | }
79 | }
80 | return student;
81 | }
82 |
83 | public void createStudent(Student student)
84 | {
85 | Connection conn = null;
86 | try
87 | {
88 | conn = getDatabaseConnection();
89 | String sql = "INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)";
90 | PreparedStatement pstmt = conn.prepareStatement(sql);
91 | pstmt.setInt(1, student.getStudId());
92 | pstmt.setString(2, student.getName());
93 | pstmt.setString(3, student.getEmail());
94 | pstmt.setDate(4, new java.sql.Date(student.getDob().getTime()));
95 | pstmt.executeUpdate();
96 |
97 | } catch (SQLException e)
98 | {
99 | throw new RuntimeException(e);
100 | }
101 | finally
102 | {
103 | if(conn!= null){
104 | try {
105 | conn.close();
106 | } catch (SQLException e){ }
107 | }
108 | }
109 | }
110 |
111 | public void updateStudent(Student student)
112 | {
113 | Connection conn = null;
114 | try
115 | {
116 | conn = getDatabaseConnection();
117 | conn = getDatabaseConnection();
118 | String sql = "UPDATE STUDENTS SET NAME=?,EMAIL=?,DOB=? WHERE STUD_ID=?";
119 | PreparedStatement pstmt = conn.prepareStatement(sql);
120 | pstmt.setString(1, student.getName());
121 | pstmt.setString(2, student.getEmail());
122 | pstmt.setDate(3, new java.sql.Date(student.getDob().getTime()));
123 | pstmt.setInt(4, student.getStudId());
124 | pstmt.executeUpdate();
125 |
126 | } catch (SQLException e)
127 | {
128 | throw new RuntimeException(e.getCause());
129 | }
130 | finally
131 | {
132 | if(conn!= null){
133 | try {
134 | conn.close();
135 | } catch (SQLException e){ }
136 | }
137 | }
138 | }
139 |
140 | protected Connection getDatabaseConnection() throws SQLException
141 | {
142 | try
143 | {
144 | Class.forName(JdbcStudentService.DRIVER);
145 | return DriverManager.getConnection(JdbcStudentService.URL,
146 | JdbcStudentService.USERNAME,
147 | JdbcStudentService.PASSWORD);
148 | } catch (SQLException e)
149 | {
150 | throw e;
151 | } catch (Exception e)
152 | {
153 | throw new RuntimeException(e.getCause());
154 | }
155 | }
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/com/mybatis3/services/StudentService.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.List;
4 |
5 | import org.apache.ibatis.session.SqlSession;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import com.mybatis3.domain.Student;
10 | import com.mybatis3.mappers.StudentMapper;
11 | import com.mybatis3.util.MyBatisSqlSessionFactory;
12 |
13 |
14 | /**
15 | * @author Siva
16 | *
17 | */
18 | public class StudentService
19 | {
20 | private Logger logger = LoggerFactory.getLogger(getClass());
21 |
22 | public List findAllStudents()
23 | {
24 | SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
25 | try {
26 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
27 | return studentMapper.findAllStudents();
28 | } finally {
29 | sqlSession.close();
30 | }
31 | }
32 |
33 | public Student findStudentById(Integer studId)
34 | {
35 | logger.debug("Select Student By ID :{}", studId);
36 | SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
37 | try {
38 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
39 | return studentMapper.findStudentById(studId);
40 | //return sqlSession.selectOne("com.mybatis3.StudentMapper.findStudentById", studId);
41 | } finally {
42 | sqlSession.close();
43 | }
44 | }
45 |
46 | public void createStudent(Student student)
47 | {
48 | SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
49 | try {
50 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
51 | studentMapper.insertStudent(student);
52 | sqlSession.commit();
53 | } finally {
54 | sqlSession.close();
55 | }
56 | }
57 |
58 | public void updateStudent(Student student)
59 | {
60 | SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
61 | try {
62 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
63 | studentMapper.updateStudent(student);
64 | sqlSession.commit();
65 | } finally {
66 | sqlSession.close();
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/com/mybatis3/util/MyBatisSqlSessionFactory.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.util;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.sql.Connection;
6 | import java.sql.DriverManager;
7 | import java.util.Properties;
8 |
9 | import org.apache.ibatis.datasource.DataSourceFactory;
10 | import org.apache.ibatis.io.Resources;
11 | import org.apache.ibatis.session.SqlSession;
12 | import org.apache.ibatis.session.SqlSessionFactory;
13 | import org.apache.ibatis.session.SqlSessionFactoryBuilder;
14 |
15 | /**
16 | * @author Siva
17 | *
18 | */
19 | public class MyBatisSqlSessionFactory
20 | {
21 | private static SqlSessionFactory sqlSessionFactory;
22 |
23 | private static final Properties PROPERTIES = new Properties();
24 |
25 | static
26 | {
27 | try {
28 | InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
29 | PROPERTIES.load(is);
30 | } catch (IOException e) {
31 | e.printStackTrace();
32 | }
33 | }
34 |
35 | public static SqlSessionFactory getSqlSessionFactory()
36 | {
37 | if(sqlSessionFactory==null)
38 | {
39 | InputStream inputStream = null;
40 | try
41 | {
42 | inputStream = Resources.getResourceAsStream("mybatis-config.xml");
43 | sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
44 | }catch (IOException e)
45 | {
46 | throw new RuntimeException(e.getCause());
47 | }finally {
48 | if(inputStream != null){
49 | try {
50 | inputStream.close();
51 | } catch (IOException e) {
52 | }
53 | }
54 | }
55 | }
56 | return sqlSessionFactory;
57 | }
58 |
59 | public static SqlSession getSqlSession()
60 | {
61 | return getSqlSessionFactory().openSession();
62 | }
63 |
64 | public static Connection getConnection()
65 | {
66 | String driver = PROPERTIES.getProperty("jdbc.driverClassName");
67 | String url = PROPERTIES.getProperty("jdbc.url");
68 | String username = PROPERTIES.getProperty("jdbc.username");
69 | String password = PROPERTIES.getProperty("jdbc.password");
70 | Connection connection = null;
71 | try {
72 | Class.forName(driver);
73 | connection = DriverManager.getConnection(url, username, password);
74 | } catch (Exception e) {
75 | throw new RuntimeException(e);
76 | }
77 | return connection;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/chapter01/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 | ################### DataSource Configuration ##########################
4 |
5 | jdbc.driverClassName=com.mysql.jdbc.Driver
6 | jdbc.url=jdbc:mysql://localhost:3306/elearning
7 | jdbc.username=root
8 | jdbc.password=admin
9 |
--------------------------------------------------------------------------------
/chapter01/src/main/resources/com/mybatis3/mappers/StudentMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
22 |
23 |
24 | INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
25 |
26 |
27 |
28 | UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
29 |
30 |
31 |
--------------------------------------------------------------------------------
/chapter01/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=INFO, stdout
2 |
3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5 | log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
6 |
7 | log4j.logger.com.mybatis3=DEBUG
--------------------------------------------------------------------------------
/chapter01/src/main/resources/mybatis-config.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/chapter01/src/main/resources/sql/create_tables.sql:
--------------------------------------------------------------------------------
1 |
2 | CREATE TABLE ADDRESSES
3 | (
4 | ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
5 | STREET VARCHAR(50) NOT NULL,
6 | CITY VARCHAR(50) NOT NULL,
7 | STATE VARCHAR(50) NOT NULL,
8 | ZIP VARCHAR(10) DEFAULT NULL,
9 | COUNTRY VARCHAR(50) NOT NULL,
10 | PRIMARY KEY (ADDR_ID)
11 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
12 |
13 | CREATE TABLE STUDENTS
14 | (
15 | STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
16 | NAME VARCHAR(50) NOT NULL,
17 | EMAIL VARCHAR(50) NOT NULL,
18 | PHONE VARCHAR(15) DEFAULT NULL,
19 | DOB DATE DEFAULT NULL,
20 | BIO LONGTEXT DEFAULT NULL,
21 | PIC BLOB DEFAULT NULL,
22 | ADDR_ID INT(11) DEFAULT NULL,
23 | PRIMARY KEY (STUD_ID),
24 | CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
25 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
26 |
27 | CREATE TABLE TUTORS
28 | (
29 | TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
30 | NAME VARCHAR(50) NOT NULL,
31 | EMAIL VARCHAR(50) NOT NULL,
32 | PHONE VARCHAR(15) DEFAULT NULL,
33 | DOB DATE DEFAULT NULL,
34 | BIO LONGTEXT DEFAULT NULL,
35 | PIC BLOB DEFAULT NULL,
36 | ADDR_ID INT(11) DEFAULT NULL,
37 | PRIMARY KEY (TUTOR_ID),
38 | CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
39 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
40 |
41 |
42 | CREATE TABLE COURSES
43 | (
44 | COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
45 | NAME VARCHAR(100) NOT NULL,
46 | DESCRIPTION VARCHAR(512) DEFAULT NULL,
47 | START_DATE DATE DEFAULT NULL,
48 | END_DATE DATE DEFAULT NULL,
49 | TUTOR_ID INT(11) NOT NULL,
50 | PRIMARY KEY (COURSE_ID),
51 | CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
52 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
53 |
54 |
55 | CREATE TABLE COURSE_ENROLLMENT
56 | (
57 | COURSE_ID INT(11) NOT NULL,
58 | STUD_ID INT(11) NOT NULL,
59 | PRIMARY KEY (COURSE_ID,STUD_ID),
60 | CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
61 | CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
62 | ) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
63 |
64 |
65 |
66 | CREATE TABLE USER_PICS
67 | (
68 | ID INT(11) NOT NULL AUTO_INCREMENT,
69 | NAME VARCHAR(50) DEFAULT NULL,
70 | PIC BLOB,
71 | BIO LONGTEXT,
72 | PRIMARY KEY (ID)
73 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
74 |
75 |
76 |
--------------------------------------------------------------------------------
/chapter01/src/main/resources/sql/drop_tables.sql:
--------------------------------------------------------------------------------
1 |
2 | DROP TABLE IF EXISTS USER_PICS;
3 | DROP TABLE IF EXISTS COURSE_ENROLLMENT;
4 | DROP TABLE IF EXISTS COURSES;
5 | DROP TABLE IF EXISTS TUTORS;
6 | DROP TABLE IF EXISTS STUDENTS;
7 | DROP TABLE IF EXISTS ADDRESSES;
8 |
9 |
--------------------------------------------------------------------------------
/chapter01/src/main/resources/sql/sample_data.sql:
--------------------------------------------------------------------------------
1 |
2 |
3 | --Sample data for table ADDRESSES
4 |
5 | INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
6 | (1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
7 | (2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
8 | (3,'710 N Cable Rd','Lima','OH','45825','Allen'),
9 | (4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
10 |
11 | -- Sample data for table STUDENTS
12 |
13 | INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
14 | (1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
15 | (2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
16 |
17 | -- Sample data for table TUTORS
18 |
19 | INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
20 | (1,'John','john@gmail.com','111-222-3333','1980-05-20',NULL,NULL,1),
21 | (2,'Paul','paul@gmail.com','123-321-4444','1981-03-15',NULL,NULL,2);
22 |
23 | -- Sample data for table courses
24 |
25 | INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
26 | (1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
27 | (2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
28 | (3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
29 |
30 | -- Sample data for table COURSE_ENROLLMENT
31 |
32 | INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
33 | (1,1),
34 | (1,2),
35 | (2,2);
36 |
37 |
--------------------------------------------------------------------------------
/chapter01/src/test/java/com/mybatis3/services/StudentServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.Date;
4 | import java.util.List;
5 |
6 | import org.junit.AfterClass;
7 | import static org.junit.Assert.*;
8 | import org.junit.BeforeClass;
9 | import org.junit.Test;
10 |
11 | import com.mybatis3.domain.Student;
12 |
13 |
14 |
15 | /**
16 | * @author Siva
17 | *
18 | */
19 | public class StudentServiceTest
20 | {
21 | private static StudentService studentService;
22 |
23 | @BeforeClass
24 | public static void setup()
25 | {
26 | studentService = new StudentService();
27 | TestDataPopulator.initDatabase();
28 | }
29 | @AfterClass
30 | public static void teardown()
31 | {
32 | studentService = null;
33 | }
34 |
35 | @Test
36 | public void testFindAllStudents()
37 | {
38 | List students = studentService.findAllStudents();
39 | assertNotNull(students);
40 | for (Student student : students)
41 | {
42 | assertNotNull(student);
43 | //System.out.println(student);
44 | }
45 |
46 | }
47 |
48 | @Test
49 | public void testFindStudentById()
50 | {
51 | Student student = studentService.findStudentById(1);
52 | assertNotNull(student);
53 | }
54 |
55 | @Test
56 | public void testCreateUStudent()
57 | {
58 | Student student = new Student();
59 | int id = 4;
60 | student.setStudId(id);
61 | student.setName("student_"+id);
62 | student.setEmail("student_"+id+"gmail.com");
63 | student.setDob(new Date());
64 | studentService.createStudent(student);
65 | Student newStudent = studentService.findStudentById(id);
66 | assertNotNull(newStudent);
67 | assertEquals("student_"+id, newStudent.getName());
68 | assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
69 | }
70 |
71 | @Test
72 | public void testUpdateStudent()
73 | {
74 | int id = 2;
75 | Student student =studentService.findStudentById(id);
76 | student.setStudId(id);
77 | student.setName("student_"+id);
78 | student.setEmail("student_"+id+"gmail.com");
79 | Date now = new Date();
80 | student.setDob(now);
81 | studentService.updateStudent(student);
82 | Student updatedStudent = studentService.findStudentById(id);
83 | assertNotNull(updatedStudent);
84 | assertEquals("student_"+id, updatedStudent.getName());
85 | assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());
86 |
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/chapter01/src/test/java/com/mybatis3/services/TestDataPopulator.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.services;
5 |
6 | import java.io.Reader;
7 | import java.sql.Connection;
8 |
9 | import org.apache.ibatis.io.Resources;
10 | import org.apache.ibatis.jdbc.ScriptRunner;
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | import com.mybatis3.util.MyBatisSqlSessionFactory;
15 |
16 | /**
17 | * @author Siva
18 | *
19 | */
20 | public class TestDataPopulator
21 | {
22 | private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
23 |
24 | public static void main(String[] args) {
25 | initDatabase();
26 | }
27 |
28 | public static void initDatabase()
29 | {
30 | Connection connection = null;
31 | Reader reader = null;
32 | try {
33 | connection = MyBatisSqlSessionFactory.getConnection();
34 | ScriptRunner scriptRunner = new ScriptRunner(connection);
35 | reader = Resources.getResourceAsReader("sql/drop_tables.sql");
36 | scriptRunner.runScript(reader);
37 | logger.info("drop_tables.sql executed successfully");
38 | reader = Resources.getResourceAsReader("sql/create_tables.sql");
39 | scriptRunner.runScript(reader );
40 | logger.info("create_tables.sql executed successfully");
41 | reader = Resources.getResourceAsReader("sql/sample_data.sql");
42 | scriptRunner.runScript(reader );
43 | logger.info("sample_data.sql executed successfully");
44 | connection.commit();
45 | reader.close();
46 | scriptRunner.closeConnection();
47 | } catch (Exception e) {
48 | throw new RuntimeException(e);
49 | }
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/chapter01/src/test/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=DEBUG, stdout
2 |
3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5 | log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
6 |
7 | log4j.logger.com.mybatis3=DEBUG
--------------------------------------------------------------------------------
/chapter02/README.txt:
--------------------------------------------------------------------------------
1 | Chapter 2: Bootstrapping MyBatis
2 | =======================================
3 | This module, chapter02, is a maven based java project to demonstrate the following approaches to configure and bootstrap MyBatis.
4 | . Configuration using XML
5 | . Configuration using Java API.
6 |
7 | Note: You can create MySQL Database tables using scripts in src/main/resources/sql folder.
8 |
9 | How to Run:
10 | 1. Configure Database Connection properties like hostname, username and password in src/main/resources/application.properties file.
11 | 2. Run StudentServiceTest JUnit Test class by using the appropriate configuration style in com.mybatis3.services.StudentServiceTest.setup() method.
12 |
--------------------------------------------------------------------------------
/chapter02/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 | 4.0.0
7 |
8 | com.mybatis3
9 | chapter02
10 | 0.0.1
11 | chapter02
12 | http://www.mybatis.org
13 | MyBatis Book Chapter 02
14 |
15 |
16 | UTF-8
17 | 1.6
18 | 4.11
19 | 1.7.5
20 | 1.2.17
21 | 3.2.2
22 | 5.1.21
23 | 2.3.2
24 |
25 |
26 |
27 | ${project.artifactId}
28 |
29 |
30 | org.apache.maven.plugins
31 | maven-compiler-plugin
32 | ${maven.compiler.plugin}
33 |
34 | ${java.version}
35 | ${java.version}
36 | ${project.build.sourceEncoding}
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | junit
47 | junit
48 | ${junit.version}
49 | test
50 |
51 |
52 |
53 | org.slf4j
54 | slf4j-api
55 | ${slf4j.version}
56 |
57 |
58 |
59 | org.slf4j
60 | slf4j-log4j12
61 | ${slf4j.version}
62 | runtime
63 |
64 |
65 |
66 | log4j
67 | log4j
68 | ${log4j.version}
69 | runtime
70 |
71 |
72 |
73 | org.mybatis
74 | mybatis
75 | ${mybatis.version}
76 |
77 |
78 |
79 | mysql
80 | mysql-connector-java
81 | ${mysql.version}
82 | runtime
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/domain/PhoneNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.domain;
5 |
6 |
7 | /**
8 | * @author Siva
9 | *
10 | */
11 | public class PhoneNumber
12 | {
13 | private String countryCode;
14 | private String stateCode;
15 | private String number;
16 |
17 | public PhoneNumber() {
18 | }
19 |
20 | public PhoneNumber(String countryCode, String stateCode, String number) {
21 | super();
22 | this.countryCode = countryCode;
23 | this.stateCode = stateCode;
24 | this.number = number;
25 | }
26 |
27 | public PhoneNumber(String string) {
28 | if(string != null){
29 | String[] parts = string.split("-");
30 | if(parts.length>0) this.countryCode=parts[0];
31 | if(parts.length>1) this.stateCode=parts[1];
32 | if(parts.length>2) this.number=parts[2];
33 |
34 | }
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return this.getAsString();
40 | }
41 |
42 | public String getCountryCode() {
43 | return countryCode;
44 | }
45 |
46 | public void setCountryCode(String countryCode) {
47 | this.countryCode = countryCode;
48 | }
49 |
50 | public String getStateCode() {
51 | return stateCode;
52 | }
53 |
54 | public void setStateCode(String stateCode) {
55 | this.stateCode = stateCode;
56 | }
57 |
58 | public String getNumber() {
59 | return number;
60 | }
61 |
62 | public void setNumber(String number) {
63 | this.number = number;
64 | }
65 |
66 | public String getAsString() {
67 | return countryCode+"-"+stateCode+"-"+number;
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/domain/Student.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.util.Date;
4 |
5 | import org.apache.ibatis.type.Alias;
6 |
7 |
8 | /**
9 | * @author Siva
10 | *
11 | */
12 | @Alias("Student")
13 | public class Student
14 | {
15 | private Integer studId;
16 | private String name;
17 | private String email;
18 | private Date dob;
19 |
20 | public Student() {
21 |
22 | }
23 |
24 | public Student(Integer studId) {
25 | this.studId = studId;
26 | }
27 |
28 | public Student(Integer studId, String name, String email, Date dob) {
29 | this.studId = studId;
30 | this.name = name;
31 | this.email = email;
32 | this.dob = dob;
33 | }
34 |
35 | @Override
36 | public String toString() {
37 | return "Student [studId=" + studId + ", name=" + name + ", email="
38 | + email + ", dob=" + dob + "]";
39 | }
40 |
41 | public Integer getStudId() {
42 | return studId;
43 | }
44 | public void setStudId(Integer studId) {
45 | this.studId = studId;
46 | }
47 | public String getName() {
48 | return name;
49 | }
50 | public void setName(String name) {
51 | this.name = name;
52 | }
53 | public String getEmail() {
54 | return email;
55 | }
56 | public void setEmail(String email) {
57 | this.email = email;
58 | }
59 | public Date getDob() {
60 | return dob;
61 | }
62 | public void setDob(Date dob) {
63 | this.dob = dob;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/mappers/StudentMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import java.util.List;
4 |
5 | import com.mybatis3.domain.Student;
6 |
7 |
8 | /**
9 | * @author Siva
10 | *
11 | */
12 | public interface StudentMapper
13 | {
14 |
15 | List findAllStudents();
16 |
17 | Student findStudentById(Integer id);
18 |
19 | void insertStudent(Student student);
20 |
21 | void updateStudent(Student student);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/services/StudentService.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.List;
4 |
5 | import org.apache.ibatis.session.SqlSession;
6 | import org.apache.ibatis.session.SqlSessionFactory;
7 | import org.slf4j.Logger;
8 | import org.slf4j.LoggerFactory;
9 |
10 | import com.mybatis3.domain.Student;
11 | import com.mybatis3.mappers.StudentMapper;
12 |
13 |
14 | public class StudentService
15 | {
16 | private Logger logger = LoggerFactory.getLogger(getClass());
17 |
18 | private SqlSessionFactory factory;
19 | public StudentService(SqlSessionFactory factory) {
20 | this.factory = factory;
21 | }
22 |
23 | protected SqlSession openSqlSession()
24 | {
25 | return factory.openSession();
26 | }
27 | public List findAllStudents()
28 | {
29 | SqlSession sqlSession = openSqlSession();
30 | try {
31 | //sqlSession.selectList("com.mybatis3.mappers.StudentMapper.findAllStudents");
32 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
33 | return studentMapper.findAllStudents();
34 | } finally {
35 | sqlSession.close();
36 | }
37 | }
38 |
39 | public Student findStudentById(Integer studId)
40 | {
41 | logger.debug("Select Student By ID :{}", studId);
42 | SqlSession sqlSession = openSqlSession();
43 | try {
44 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
45 | return studentMapper.findStudentById(studId);
46 | } finally {
47 | sqlSession.close();
48 | }
49 | }
50 |
51 | public Student createStudent(Student student)
52 | {
53 | SqlSession sqlSession = openSqlSession();
54 | try {
55 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
56 | studentMapper.insertStudent(student);
57 | sqlSession.commit();
58 | return student;
59 | } finally {
60 | sqlSession.close();
61 | }
62 | }
63 |
64 | public void updateStudent(Student student)
65 | {
66 | SqlSession sqlSession = openSqlSession();
67 | try {
68 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
69 | studentMapper.updateStudent(student);
70 | sqlSession.commit();
71 | } finally {
72 | sqlSession.close();
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.typehandlers;
5 |
6 | import java.sql.CallableStatement;
7 | import java.sql.PreparedStatement;
8 | import java.sql.ResultSet;
9 | import java.sql.SQLException;
10 |
11 | import org.apache.ibatis.type.BaseTypeHandler;
12 | import org.apache.ibatis.type.JdbcType;
13 |
14 | import com.mybatis3.domain.PhoneNumber;
15 |
16 |
17 | /**
18 | * @author Siva
19 | *
20 | */
21 | public class PhoneTypeHandler extends BaseTypeHandler{
22 |
23 | @Override
24 | public void setNonNullParameter(PreparedStatement ps, int i,
25 | PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
26 | ps.setString(i, parameter.getAsString());
27 | }
28 |
29 | @Override
30 | public PhoneNumber getNullableResult(ResultSet rs, String columnName)
31 | throws SQLException {
32 | return new PhoneNumber(rs.getString(columnName));
33 | }
34 |
35 | @Override
36 | public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
37 | throws SQLException {
38 | return new PhoneNumber(rs.getString(columnIndex));
39 | }
40 |
41 | @Override
42 | public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
43 | throws SQLException {
44 | return new PhoneNumber(cs.getString(columnIndex));
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/util/DataSourceFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.util;
5 |
6 | import java.io.IOException;
7 | import java.io.InputStream;
8 | import java.util.Properties;
9 |
10 | import javax.naming.InitialContext;
11 | import javax.naming.NamingException;
12 | import javax.sql.DataSource;
13 |
14 | import org.apache.ibatis.datasource.pooled.PooledDataSource;
15 |
16 | /**
17 | * @author Siva
18 | *
19 | */
20 | public class DataSourceFactory
21 | {
22 | private static final Properties PROPERTIES = new Properties();
23 |
24 | static
25 | {
26 | try {
27 | InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
28 | PROPERTIES.load(is);
29 | } catch (IOException e) {
30 | e.printStackTrace();
31 | }
32 | }
33 |
34 | public static DataSource getDataSource()
35 | {
36 | String driver = PROPERTIES.getProperty("jdbc.driverClassName");
37 | String url = PROPERTIES.getProperty("jdbc.url");
38 | String username = PROPERTIES.getProperty("jdbc.username");
39 | String password = PROPERTIES.getProperty("jdbc.password");
40 | PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);
41 | return dataSource;
42 | }
43 |
44 | public static DataSource getJNDIDataSource()
45 | {
46 | String dataSourceJNDIName = "java:comp/env/jdbc/MyBatisDemoDS";
47 | try
48 | {
49 | InitialContext ctx = new InitialContext();
50 | DataSource dataSource = (DataSource) ctx.lookup(dataSourceJNDIName);
51 | return dataSource;
52 | }
53 | catch (NamingException e)
54 | {
55 | throw new RuntimeException(e);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/com/mybatis3/util/MyBatisUtil.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.util;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 |
6 | import javax.sql.DataSource;
7 |
8 | import org.apache.ibatis.io.Resources;
9 | import org.apache.ibatis.mapping.Environment;
10 | import org.apache.ibatis.session.Configuration;
11 | import org.apache.ibatis.session.SqlSessionFactory;
12 | import org.apache.ibatis.session.SqlSessionFactoryBuilder;
13 | import org.apache.ibatis.transaction.TransactionFactory;
14 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
15 |
16 | import com.mybatis3.domain.Student;
17 | import com.mybatis3.mappers.StudentMapper;
18 | import com.mybatis3.typehandlers.PhoneTypeHandler;
19 |
20 |
21 | /**
22 | * @author Siva
23 | *
24 | */
25 | public class MyBatisUtil
26 | {
27 | private static SqlSessionFactory xmlSqlSessionFactory;
28 | private static SqlSessionFactory javaSqlSessionFactory;
29 |
30 | public static SqlSessionFactory getSqlSessionFactoryUsingXML()
31 | {
32 | if(xmlSqlSessionFactory==null)
33 | {
34 | InputStream inputStream;
35 | try
36 | {
37 | inputStream = Resources.getResourceAsStream("mybatis-config.xml");
38 | xmlSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
39 | }catch (IOException e)
40 | {
41 | throw new RuntimeException(e);
42 | }
43 | }
44 | return xmlSqlSessionFactory;
45 | }
46 |
47 | public static SqlSessionFactory getSqlSessionFactoryUsingJavaAPI()
48 | {
49 | if(javaSqlSessionFactory==null)
50 | {
51 | try
52 | {
53 | DataSource dataSource = DataSourceFactory.getDataSource();
54 | TransactionFactory transactionFactory = new JdbcTransactionFactory();
55 | Environment environment = new Environment("development", transactionFactory, dataSource);
56 | Configuration configuration = new Configuration(environment);
57 | configuration.getTypeAliasRegistry().registerAlias("student", Student.class);
58 | configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.class);
59 | configuration.addMapper(StudentMapper.class);
60 | javaSqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
61 |
62 | }catch (Exception e)
63 | {
64 | throw new RuntimeException(e);
65 | }
66 | }
67 | return javaSqlSessionFactory;
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 | ################### DataSource Configuration ##########################
4 |
5 | jdbc.driverClassName=com.mysql.jdbc.Driver
6 | jdbc.url=jdbc:mysql://localhost:3306/elearning
7 | jdbc.username=root
8 | jdbc.password=admin
9 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/com/mybatis3/mappers/StudentMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
22 |
23 |
24 | INSERT INTO STUDENTS(NAME,EMAIL,DOB) VALUES(#{name},#{email},#{dob})
25 |
26 |
27 |
28 | UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
29 |
30 |
31 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/full-mybatis-config.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=INFO, stdout
2 |
3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5 | log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
6 |
7 | log4j.logger.com.mybatis3=DEBUG
--------------------------------------------------------------------------------
/chapter02/src/main/resources/mybatis-config.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/sql/create_tables.sql:
--------------------------------------------------------------------------------
1 |
2 | CREATE TABLE ADDRESSES
3 | (
4 | ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
5 | STREET VARCHAR(50) NOT NULL,
6 | CITY VARCHAR(50) NOT NULL,
7 | STATE VARCHAR(50) NOT NULL,
8 | ZIP VARCHAR(10) DEFAULT NULL,
9 | COUNTRY VARCHAR(50) NOT NULL,
10 | PRIMARY KEY (ADDR_ID)
11 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
12 |
13 | CREATE TABLE STUDENTS
14 | (
15 | STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
16 | NAME VARCHAR(50) NOT NULL,
17 | EMAIL VARCHAR(50) NOT NULL,
18 | PHONE VARCHAR(15) DEFAULT NULL,
19 | DOB DATE DEFAULT NULL,
20 | BIO LONGTEXT DEFAULT NULL,
21 | PIC BLOB DEFAULT NULL,
22 | ADDR_ID INT(11) DEFAULT NULL,
23 | PRIMARY KEY (STUD_ID),
24 | CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
25 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
26 |
27 | CREATE TABLE TUTORS
28 | (
29 | TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
30 | NAME VARCHAR(50) NOT NULL,
31 | EMAIL VARCHAR(50) NOT NULL,
32 | PHONE VARCHAR(15) DEFAULT NULL,
33 | DOB DATE DEFAULT NULL,
34 | BIO LONGTEXT DEFAULT NULL,
35 | PIC BLOB DEFAULT NULL,
36 | ADDR_ID INT(11) DEFAULT NULL,
37 | PRIMARY KEY (TUTOR_ID),
38 | CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
39 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
40 |
41 |
42 | CREATE TABLE COURSES
43 | (
44 | COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
45 | NAME VARCHAR(100) NOT NULL,
46 | DESCRIPTION VARCHAR(512) DEFAULT NULL,
47 | START_DATE DATE DEFAULT NULL,
48 | END_DATE DATE DEFAULT NULL,
49 | TUTOR_ID INT(11) NOT NULL,
50 | PRIMARY KEY (COURSE_ID),
51 | CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
52 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
53 |
54 |
55 | CREATE TABLE COURSE_ENROLLMENT
56 | (
57 | COURSE_ID INT(11) NOT NULL,
58 | STUD_ID INT(11) NOT NULL,
59 | PRIMARY KEY (COURSE_ID,STUD_ID),
60 | CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
61 | CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
62 | ) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
63 |
64 |
65 |
66 | CREATE TABLE USER_PICS
67 | (
68 | ID INT(11) NOT NULL AUTO_INCREMENT,
69 | NAME VARCHAR(50) DEFAULT NULL,
70 | PIC BLOB,
71 | BIO LONGTEXT,
72 | PRIMARY KEY (ID)
73 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
74 |
75 |
76 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/sql/drop_tables.sql:
--------------------------------------------------------------------------------
1 |
2 | DROP TABLE IF EXISTS USER_PICS;
3 | DROP TABLE IF EXISTS COURSE_ENROLLMENT;
4 | DROP TABLE IF EXISTS COURSES;
5 | DROP TABLE IF EXISTS TUTORS;
6 | DROP TABLE IF EXISTS STUDENTS;
7 | DROP TABLE IF EXISTS ADDRESSES;
8 |
9 |
--------------------------------------------------------------------------------
/chapter02/src/main/resources/sql/sample_data.sql:
--------------------------------------------------------------------------------
1 |
2 |
3 | --Sample data for table ADDRESSES
4 |
5 | INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
6 | (1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
7 | (2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
8 | (3,'710 N Cable Rd','Lima','OH','45825','Allen'),
9 | (4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
10 |
11 | -- Sample data for table STUDENTS
12 |
13 | INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
14 | (1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
15 | (2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
16 |
17 | -- Sample data for table TUTORS
18 |
19 | INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
20 | (1,'John','john@gmail.com','111-222-3333','1980-05-20',NULL,NULL,1),
21 | (2,'Paul','paul@gmail.com','123-321-4444','1981-03-15',NULL,NULL,2);
22 |
23 | -- Sample data for table courses
24 |
25 | INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
26 | (1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
27 | (2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
28 | (3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
29 |
30 | -- Sample data for table COURSE_ENROLLMENT
31 |
32 | INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
33 | (1,1),
34 | (1,2),
35 | (2,2);
36 |
37 |
--------------------------------------------------------------------------------
/chapter02/src/test/java/com/mybatis3/services/StudentServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 |
6 | import java.util.Date;
7 | import java.util.List;
8 |
9 | import org.apache.ibatis.session.SqlSessionFactory;
10 | import org.junit.AfterClass;
11 | import org.junit.BeforeClass;
12 | import org.junit.Test;
13 |
14 | import com.mybatis3.domain.Student;
15 | import com.mybatis3.util.MyBatisUtil;
16 |
17 | public class StudentServiceTest
18 | {
19 | private static StudentService studentService;
20 |
21 | @BeforeClass
22 | public static void setup()
23 | {
24 | TestDataPopulator.initDatabase();
25 |
26 | SqlSessionFactory sqlSessionFactory = null;
27 | //Use this if you want XML based configuration
28 | sqlSessionFactory = MyBatisUtil.getSqlSessionFactoryUsingXML();
29 |
30 | //Use this if you want to use Java API configuration
31 | //sqlSessionFactory = MyBatisUtil.getSqlSessionFactoryUsingJavaAPI();
32 | studentService = new StudentService(sqlSessionFactory);
33 | }
34 |
35 | @AfterClass
36 | public static void teardown()
37 | {
38 | studentService = null;
39 | }
40 |
41 | @Test
42 | public void testFindAllStudents()
43 | {
44 | List students = studentService.findAllStudents();
45 | assertNotNull(students);
46 | for (Student student : students)
47 | {
48 | assertNotNull(student);
49 | //System.out.println(student);
50 | }
51 |
52 | }
53 |
54 | @Test
55 | public void testFindStudentById()
56 | {
57 | Student student = studentService.findStudentById(1);
58 | assertNotNull(student);
59 | }
60 |
61 | @Test
62 | public void testCreateUStudent()
63 | {
64 | Student student = new Student();
65 | int id = 4;
66 | student.setStudId(id);
67 | student.setName("student_"+id);
68 | student.setEmail("student_"+id+"gmail.com");
69 | student.setDob(new Date());
70 | Student newStudent = studentService.createStudent(student);
71 | assertNotNull(newStudent);
72 | assertEquals("student_"+id, newStudent.getName());
73 | assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
74 | }
75 |
76 | @Test
77 | public void testUpdateStudent()
78 | {
79 | int id = 2;
80 | Student student =studentService.findStudentById(id);
81 | student.setStudId(id);
82 | student.setName("student_"+id);
83 | student.setEmail("student_"+id+"gmail.com");
84 | Date now = new Date();
85 | student.setDob(now);
86 | studentService.updateStudent(student);
87 | Student updatedStudent = studentService.findStudentById(id);
88 | assertNotNull(updatedStudent);
89 | assertEquals("student_"+id, updatedStudent.getName());
90 | assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());
91 |
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/chapter02/src/test/java/com/mybatis3/services/TestDataPopulator.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.services;
5 |
6 | import java.io.Reader;
7 | import java.sql.Connection;
8 |
9 | import org.apache.ibatis.io.Resources;
10 | import org.apache.ibatis.jdbc.ScriptRunner;
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | import com.mybatis3.util.DataSourceFactory;
15 |
16 |
17 | /**
18 | * @author Siva
19 | *
20 | */
21 | public class TestDataPopulator
22 | {
23 | private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
24 |
25 | public static void main(String[] args) {
26 | initDatabase();
27 | }
28 |
29 | public static void initDatabase()
30 | {
31 | Connection connection = null;
32 | Reader reader = null;
33 | try {
34 | connection = DataSourceFactory.getDataSource().getConnection();
35 | ScriptRunner scriptRunner = new ScriptRunner(connection);
36 | reader = Resources.getResourceAsReader("sql/drop_tables.sql");
37 | scriptRunner.runScript(reader);
38 | logger.info("drop_tables.sql executed successfully");
39 | reader = Resources.getResourceAsReader("sql/create_tables.sql");
40 | scriptRunner.runScript(reader );
41 | logger.info("create_tables.sql executed successfully");
42 | reader = Resources.getResourceAsReader("sql/sample_data.sql");
43 | scriptRunner.runScript(reader );
44 | logger.info("sample_data.sql executed successfully");
45 | connection.commit();
46 | reader.close();
47 | scriptRunner.closeConnection();
48 | } catch (Exception e) {
49 | throw new RuntimeException(e);
50 | }
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/chapter03/README.txt:
--------------------------------------------------------------------------------
1 | Chapter 3: SQL Mappers using XML
2 | =================================
3 | This chapter describes mapping SQL statements and query results to java beans in SQL Mappers using XML based approach.
4 | Topics covered:
5 | • CRUD Mapping
6 | • ResultSet Mapping
7 | • One-To-One, One-To-Many mappings
8 | • Dynamic SQL mapping
9 |
10 | How to Run:
11 | 1. Configure Database Connection properties like hostname, username and password in src/main/resources/application.properties file.
12 | 2. Run JUnit Test classes in com.mybatis3.services package under src/test/java/ folder.
13 |
14 |
--------------------------------------------------------------------------------
/chapter03/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 | 4.0.0
7 |
8 | com.mybatis3
9 | chapter03
10 | 0.0.1
11 | chapter03
12 | http://www.mybatis.org
13 | MyBatis Book Chapter 03
14 |
15 |
16 | UTF-8
17 | 1.6
18 | 4.11
19 | 1.7.5
20 | 1.2.17
21 | 3.2.2
22 | 5.1.21
23 | 2.3.2
24 |
25 |
26 |
27 | ${project.artifactId}
28 |
29 |
30 | org.apache.maven.plugins
31 | maven-compiler-plugin
32 | ${maven.compiler.plugin}
33 |
34 | ${java.version}
35 | ${java.version}
36 | ${project.build.sourceEncoding}
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | junit
47 | junit
48 | ${junit.version}
49 | test
50 |
51 |
52 |
53 | org.slf4j
54 | slf4j-api
55 | ${slf4j.version}
56 |
57 |
58 |
59 | org.slf4j
60 | slf4j-log4j12
61 | ${slf4j.version}
62 | runtime
63 |
64 |
65 |
66 | log4j
67 | log4j
68 | ${log4j.version}
69 | runtime
70 |
71 |
72 |
73 | org.mybatis
74 | mybatis
75 | ${mybatis.version}
76 |
77 |
78 |
79 | mysql
80 | mysql-connector-java
81 | ${mysql.version}
82 | runtime
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/domain/Address.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * @author Siva
7 | *
8 | */
9 | public class Address implements Serializable
10 | {
11 | private static final long serialVersionUID = 1L;
12 |
13 | private Integer addrId;
14 | private String street;
15 | private String city;
16 | private String state;
17 | private String zip;
18 | private String country;
19 |
20 | @Override
21 | public String toString() {
22 | return "Address [addrId=" + addrId + ", street=" + street + ", city=" + city
23 | + ", state=" + state + ", zip=" + zip + ", country=" + country
24 | + "]";
25 | }
26 | public Address()
27 | {
28 | }
29 | public Address(Integer addrId)
30 | {
31 | this.addrId = addrId;
32 | }
33 | public Address(Integer addrId, String street, String city, String state,
34 | String zip, String country)
35 | {
36 | this.addrId = addrId;
37 | this.street = street;
38 | this.city = city;
39 | this.state = state;
40 | this.zip = zip;
41 | this.country = country;
42 | }
43 | public Integer getAddrId() {
44 | return addrId;
45 | }
46 | public void setAddrId(Integer addrId) {
47 | this.addrId = addrId;
48 | }
49 | public String getStreet()
50 | {
51 | return street;
52 | }
53 | public void setStreet(String street)
54 | {
55 | this.street = street;
56 | }
57 | public String getCity()
58 | {
59 | return city;
60 | }
61 | public void setCity(String city)
62 | {
63 | this.city = city;
64 | }
65 | public String getState()
66 | {
67 | return state;
68 | }
69 | public void setState(String state)
70 | {
71 | this.state = state;
72 | }
73 | public String getZip()
74 | {
75 | return zip;
76 | }
77 | public void setZip(String zip)
78 | {
79 | this.zip = zip;
80 | }
81 | public String getCountry()
82 | {
83 | return country;
84 | }
85 | public void setCountry(String country)
86 | {
87 | this.country = country;
88 | }
89 |
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/domain/Course.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | /**
9 | * @author Siva
10 | *
11 | */
12 | public class Course implements Serializable
13 | {
14 | private static final long serialVersionUID = 1L;
15 |
16 | private Integer courseId;
17 | private String name;
18 | private String description;
19 | private Date startDate;
20 | private Date endDate;
21 | private Tutor tutor;
22 | private List students;
23 |
24 | @Override
25 | public String toString() {
26 | return "Course [courseId=" + courseId + ", name=" + name + ", description="
27 | + description + ", startDate=" + startDate + ", endDate="
28 | + endDate + ", tutor=" + tutor + ", students=" + students + "]";
29 | }
30 | public Integer getCourseId()
31 | {
32 | return courseId;
33 | }
34 | public void setCourseId(Integer id)
35 | {
36 | this.courseId = id;
37 | }
38 | public String getName()
39 | {
40 | return name;
41 | }
42 | public void setName(String name)
43 | {
44 | this.name = name;
45 | }
46 | public String getDescription()
47 | {
48 | return description;
49 | }
50 | public void setDescription(String description)
51 | {
52 | this.description = description;
53 | }
54 | public Date getStartDate()
55 | {
56 | return startDate;
57 | }
58 | public void setStartDate(Date startDate)
59 | {
60 | this.startDate = startDate;
61 | }
62 | public Date getEndDate()
63 | {
64 | return endDate;
65 | }
66 | public void setEndDate(Date endDate)
67 | {
68 | this.endDate = endDate;
69 | }
70 | public List getStudents()
71 | {
72 | if(students == null){
73 | students = new ArrayList(0);
74 | }
75 | return students;
76 | }
77 | public void setStudents(List students)
78 | {
79 | this.students = students;
80 | }
81 | public Tutor getTutor() {
82 | return tutor;
83 | }
84 | public void setTutor(Tutor tutor) {
85 | this.tutor = tutor;
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/domain/PhoneNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.domain;
5 |
6 | import java.io.Serializable;
7 |
8 |
9 | /**
10 | * @author Siva
11 | *
12 | */
13 | public class PhoneNumber implements Serializable
14 | {
15 | private static final long serialVersionUID = 1L;
16 |
17 | private String countryCode;
18 | private String stateCode;
19 | private String number;
20 |
21 | public PhoneNumber() {
22 | }
23 |
24 | public PhoneNumber(String countryCode, String stateCode, String number) {
25 | super();
26 | this.countryCode = countryCode;
27 | this.stateCode = stateCode;
28 | this.number = number;
29 | }
30 |
31 | public PhoneNumber(String string) {
32 | if(string != null){
33 | String[] parts = string.split("-");
34 | if(parts.length>0) this.countryCode=parts[0];
35 | if(parts.length>1) this.stateCode=parts[1];
36 | if(parts.length>2) this.number=parts[2];
37 |
38 | }
39 | }
40 |
41 | /*@Override
42 | public String toString() {
43 | return this.getAsString();
44 | }*/
45 |
46 | public String getCountryCode() {
47 | return countryCode;
48 | }
49 |
50 | public void setCountryCode(String countryCode) {
51 | this.countryCode = countryCode;
52 | }
53 |
54 | public String getStateCode() {
55 | return stateCode;
56 | }
57 |
58 | public void setStateCode(String stateCode) {
59 | this.stateCode = stateCode;
60 | }
61 |
62 | public String getNumber() {
63 | return number;
64 | }
65 |
66 | public void setNumber(String number) {
67 | this.number = number;
68 | }
69 |
70 | public String getAsString() {
71 | return countryCode+"-"+stateCode+"-"+number;
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/domain/Student.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 |
5 |
6 | /**
7 | * @author Siva
8 | *
9 | */
10 | public class Student implements Serializable
11 | {
12 | private static final long serialVersionUID = 1L;
13 | private Integer studId;
14 | private String name;
15 | private String email;
16 | private PhoneNumber phone;
17 | private Address address;
18 |
19 | @Override
20 | public String toString() {
21 | return "Student [studId=" + studId + ", name=" + name + ", email=" + email
22 | + ", phone=" + (phone==null?null:phone.getAsString()) + ", address=" + address + "]";
23 | }
24 | public Student()
25 | {
26 | }
27 | public Student(Integer id)
28 | {
29 | this.studId = id;
30 | }
31 | public Integer getStudId()
32 | {
33 | return studId;
34 | }
35 | public void setStudId(Integer id)
36 | {
37 | this.studId = id;
38 | }
39 | public String getName()
40 | {
41 | return name;
42 | }
43 | public void setName(String name)
44 | {
45 | this.name = name;
46 | }
47 | public String getEmail()
48 | {
49 | return email;
50 | }
51 | public void setEmail(String email)
52 | {
53 | this.email = email;
54 | }
55 | public Address getAddress() {
56 | return address;
57 | }
58 | public void setAddress(Address address) {
59 | this.address = address;
60 | }
61 | public PhoneNumber getPhone() {
62 | return phone;
63 | }
64 | public void setPhone(PhoneNumber phone) {
65 | this.phone = phone;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/domain/Tutor.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Siva
8 | *
9 | */
10 | public class Tutor implements Serializable
11 | {
12 | private static final long serialVersionUID = 1L;
13 |
14 | private Integer tutorId;
15 | private String name;
16 | private String email;
17 | private Address address;
18 | private List courses;
19 |
20 | @Override
21 | public String toString() {
22 | return "Tutor [tutorId=" + tutorId + ", name=" + name + ", email=" + email
23 | + ", address=" + address + ", courses=" + courses + "]";
24 | }
25 | public Tutor()
26 | {
27 | }
28 | public Tutor(Integer id)
29 | {
30 | this.tutorId = id;
31 | }
32 | public Integer getTutorId()
33 | {
34 | return tutorId;
35 | }
36 | public void setTutorId(Integer id)
37 | {
38 | this.tutorId = id;
39 | }
40 | public String getName()
41 | {
42 | return name;
43 | }
44 | public void setName(String name)
45 | {
46 | this.name = name;
47 | }
48 | public String getEmail()
49 | {
50 | return email;
51 | }
52 | public void setEmail(String email)
53 | {
54 | this.email = email;
55 | }
56 | public Address getAddress()
57 | {
58 | return address;
59 | }
60 | public void setAddress(Address address)
61 | {
62 | this.address = address;
63 | }
64 | public List getCourses() {
65 | return courses;
66 | }
67 | public void setCourses(List courses) {
68 | this.courses = courses;
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/mappers/AddressMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import com.mybatis3.domain.Address;
4 |
5 |
6 |
7 | /**
8 | * @author Siva
9 | *
10 | */
11 | public interface AddressMapper
12 | {
13 | Address findAddressById(Integer id);
14 | }
15 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/mappers/CourseMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | import com.mybatis3.domain.Course;
7 |
8 |
9 |
10 | /**
11 | * @author Siva
12 | *
13 | */
14 | public interface CourseMapper
15 | {
16 |
17 | List selectCoursesByTutor(int tutorId);
18 |
19 | List searchCourses(Map map);
20 |
21 | List searchCoursesByTutors(Map map);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/mappers/StudentMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | import com.mybatis3.domain.Student;
7 |
8 |
9 |
10 | /**
11 | * @author Siva
12 | *
13 | */
14 | public interface StudentMapper
15 | {
16 |
17 | List findAllStudents();
18 |
19 | Student findStudentById(Integer id);
20 |
21 | Student selectStudentWithAddress(int id);
22 |
23 | void insertStudent(Student student);
24 |
25 | void insertStudentWithMap(Map map);
26 |
27 | void updateStudent(Student student);
28 |
29 | int deleteStudent(int id);
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/mappers/TutorMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import com.mybatis3.domain.Tutor;
4 |
5 |
6 |
7 | /**
8 | * @author Siva
9 | *
10 | */
11 | public interface TutorMapper
12 | {
13 |
14 | Tutor selectTutorWithCourses(int tutorId);
15 |
16 | Tutor selectTutorById(int tutorId);
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/services/CourseService.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | import org.apache.ibatis.session.SqlSession;
7 | import org.slf4j.Logger;
8 | import org.slf4j.LoggerFactory;
9 |
10 | import com.mybatis3.domain.Course;
11 | import com.mybatis3.mappers.CourseMapper;
12 | import com.mybatis3.util.MyBatisUtil;
13 |
14 |
15 | public class CourseService
16 | {
17 | private Logger logger = LoggerFactory.getLogger(getClass());
18 |
19 | public List searchCourses(Map map)
20 | {
21 | logger.debug("searchCourses By :"+map);
22 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
23 | try {
24 | CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
25 | return mapper.searchCourses(map);
26 | }
27 |
28 | finally {
29 | sqlSession.close();
30 | }
31 | }
32 |
33 | public List searchCoursesByTutors(Map map) {
34 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
35 | try {
36 | CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
37 | return mapper.searchCoursesByTutors(map);
38 | }
39 |
40 | finally {
41 | sqlSession.close();
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/services/StudentService.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | import org.apache.ibatis.session.SqlSession;
7 |
8 | import com.mybatis3.domain.Student;
9 | import com.mybatis3.mappers.StudentMapper;
10 | import com.mybatis3.util.MyBatisUtil;
11 |
12 |
13 | public class StudentService
14 | {
15 |
16 | public List findAllStudents()
17 | {
18 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
19 | try {
20 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
21 | return studentMapper.findAllStudents();
22 | } finally {
23 | sqlSession.close();
24 | }
25 | }
26 |
27 | public Student findStudentById(Integer id)
28 | {
29 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
30 | try {
31 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
32 | return studentMapper.findStudentById(id);
33 | } finally {
34 | sqlSession.close();
35 | }
36 | }
37 |
38 | public Student findStudentWithAddressById(int id) {
39 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
40 | try {
41 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
42 | return studentMapper.selectStudentWithAddress(id);
43 | } finally {
44 | sqlSession.close();
45 | }
46 | }
47 |
48 | public Student createStudent(Student student) {
49 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
50 | try {
51 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
52 | mapper.insertStudent(student);
53 | sqlSession.commit();
54 | return student;
55 | }
56 | catch (Exception e) {
57 | sqlSession.rollback();
58 | e.printStackTrace();
59 | throw new RuntimeException(e.getCause());
60 | }
61 | finally {
62 | sqlSession.close();
63 | }
64 | }
65 |
66 | public void createStudentWithMap(Map studentDataMap) {
67 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
68 | try {
69 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
70 | mapper.insertStudentWithMap(studentDataMap);
71 | sqlSession.commit();
72 | }
73 | catch (Exception e) {
74 | sqlSession.rollback();
75 | e.printStackTrace();
76 | throw new RuntimeException(e.getCause());
77 | }
78 | finally {
79 | sqlSession.close();
80 | }
81 | }
82 |
83 | public Student updateStudent(Student student) {
84 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
85 | try {
86 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
87 | mapper.updateStudent(student);
88 | sqlSession.commit();
89 | return student;
90 | }
91 | catch (Exception e) {
92 | sqlSession.rollback();
93 | e.printStackTrace();
94 | throw new RuntimeException(e.getCause());
95 | }
96 | finally {
97 | sqlSession.close();
98 | }
99 | }
100 |
101 | public boolean deleteStudent(int id) {
102 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
103 | try {
104 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
105 | int count = mapper.deleteStudent(id);
106 | sqlSession.commit();
107 | return count > 0;
108 | }
109 | catch (Exception e) {
110 | sqlSession.rollback();
111 | e.printStackTrace();
112 | throw new RuntimeException(e.getCause());
113 | }
114 | finally {
115 | sqlSession.close();
116 | }
117 | }
118 |
119 | }
120 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/services/TutorService.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import org.apache.ibatis.session.SqlSession;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import com.mybatis3.domain.Tutor;
8 | import com.mybatis3.mappers.TutorMapper;
9 | import com.mybatis3.util.MyBatisUtil;
10 |
11 |
12 | public class TutorService
13 | {
14 | private Logger logger = LoggerFactory.getLogger(getClass());
15 |
16 |
17 | public Tutor findTutorById(int tutorId) {
18 | logger.debug("findTutorById :"+tutorId);
19 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
20 | try {
21 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
22 | return mapper.selectTutorById(tutorId);
23 | }
24 |
25 | finally {
26 | sqlSession.close();
27 | }
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/typehandlers/PhoneTypeHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.typehandlers;
5 |
6 | import java.sql.CallableStatement;
7 | import java.sql.PreparedStatement;
8 | import java.sql.ResultSet;
9 | import java.sql.SQLException;
10 |
11 | import org.apache.ibatis.type.BaseTypeHandler;
12 | import org.apache.ibatis.type.JdbcType;
13 |
14 | import com.mybatis3.domain.PhoneNumber;
15 |
16 |
17 | /**
18 | * @author Siva
19 | *
20 | */
21 | public class PhoneTypeHandler extends BaseTypeHandler{
22 |
23 | @Override
24 | public void setNonNullParameter(PreparedStatement ps, int i,
25 | PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
26 | ps.setString(i, parameter.getAsString());
27 | }
28 |
29 | @Override
30 | public PhoneNumber getNullableResult(ResultSet rs, String columnName)
31 | throws SQLException {
32 | return new PhoneNumber(rs.getString(columnName));
33 | }
34 |
35 | @Override
36 | public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
37 | throws SQLException {
38 | return new PhoneNumber(rs.getString(columnIndex));
39 | }
40 |
41 | @Override
42 | public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
43 | throws SQLException {
44 | return new PhoneNumber(cs.getString(columnIndex));
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/com/mybatis3/util/MyBatisUtil.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.util;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.sql.Connection;
6 | import java.sql.DriverManager;
7 | import java.util.Properties;
8 |
9 | import org.apache.ibatis.datasource.DataSourceFactory;
10 | import org.apache.ibatis.io.Resources;
11 | import org.apache.ibatis.session.SqlSessionFactory;
12 | import org.apache.ibatis.session.SqlSessionFactoryBuilder;
13 |
14 | /**
15 | * @author Siva
16 | *
17 | */
18 | public class MyBatisUtil
19 | {
20 | private static final String DEFAULT_MYBATIS_CONFIG_FILE="mybatis-config.xml";
21 | private static SqlSessionFactory sqlSessionFactory;
22 |
23 | private static final Properties PROPERTIES = new Properties();
24 |
25 | static
26 | {
27 | try {
28 | InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
29 | PROPERTIES.load(is);
30 | } catch (IOException e) {
31 | e.printStackTrace();
32 | }
33 | }
34 | public static SqlSessionFactory getSqlSessionFactory()
35 | {
36 | if(sqlSessionFactory==null){
37 | //org.apache.ibatis.logging.LogFactory.useLog4JLogging();
38 | try
39 | {
40 | InputStream inputStream = Resources.getResourceAsStream(DEFAULT_MYBATIS_CONFIG_FILE);
41 | sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
42 | } catch (IOException e)
43 | {
44 | throw new RuntimeException(e.getCause());
45 | }
46 | }
47 | return sqlSessionFactory;
48 | }
49 |
50 |
51 | public static Connection getConnection()
52 | {
53 | String driver = PROPERTIES.getProperty("jdbc.driverClassName");
54 | String url = PROPERTIES.getProperty("jdbc.url");
55 | String username = PROPERTIES.getProperty("jdbc.username");
56 | String password = PROPERTIES.getProperty("jdbc.password");
57 | Connection connection = null;
58 | try {
59 | Class.forName(driver);
60 | connection = DriverManager.getConnection(url, username, password);
61 | } catch (Exception e) {
62 | throw new RuntimeException(e);
63 | }
64 | return connection;
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 | ################### DataSource Configuration ##########################
4 |
5 | jdbc.driverClassName=com.mysql.jdbc.Driver
6 | jdbc.url=jdbc:mysql://localhost:3306/elearning
7 | jdbc.username=root
8 | jdbc.password=admin
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/com/mybatis3/mappers/AddressMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
20 |
21 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/com/mybatis3/mappers/CourseMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
21 |
22 |
36 |
37 |
49 |
50 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/com/mybatis3/mappers/StudentMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
48 |
49 |
52 |
53 |
58 |
59 |
60 | insert into students(name,email,addr_id, phone)
61 | values(#{name},#{email},#{address.addrId},#{phone})
62 |
63 |
64 |
65 | insert into students(name,email,addr_id,phone)
66 | values(#{name},#{email},#{address.addrId},#{phone})
67 |
68 |
69 |
70 | update students
71 |
76 |
77 |
78 | name=#{name},
79 | email=#{email},
80 | phone=#{phone},
81 |
82 | where stud_id=#{studId}
83 |
84 |
85 |
86 | delete from students where stud_id=#{studId}
87 |
88 |
89 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/com/mybatis3/mappers/TutorMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
32 |
33 |
38 |
39 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=INFO, stdout
2 |
3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5 | log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
6 |
7 | log4j.logger.com.mybatis3=DEBUG
--------------------------------------------------------------------------------
/chapter03/src/main/resources/mybatis-config.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/sql/create_tables.sql:
--------------------------------------------------------------------------------
1 |
2 | CREATE TABLE ADDRESSES
3 | (
4 | ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
5 | STREET VARCHAR(50) NOT NULL,
6 | CITY VARCHAR(50) NOT NULL,
7 | STATE VARCHAR(50) NOT NULL,
8 | ZIP VARCHAR(10) DEFAULT NULL,
9 | COUNTRY VARCHAR(50) NOT NULL,
10 | PRIMARY KEY (ADDR_ID)
11 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
12 |
13 | CREATE TABLE STUDENTS
14 | (
15 | STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
16 | NAME VARCHAR(50) NOT NULL,
17 | EMAIL VARCHAR(50) NOT NULL,
18 | PHONE VARCHAR(15) DEFAULT NULL,
19 | DOB DATE DEFAULT NULL,
20 | GENDER VARCHAR(6) DEFAULT NULL,
21 | BIO LONGTEXT DEFAULT NULL,
22 | PIC BLOB DEFAULT NULL,
23 | ADDR_ID INT(11) DEFAULT NULL,
24 | PRIMARY KEY (STUD_ID),
25 | UNIQUE KEY UK_EMAIL (EMAIL),
26 | CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
27 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
28 |
29 | CREATE TABLE TUTORS
30 | (
31 | TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
32 | NAME VARCHAR(50) NOT NULL,
33 | EMAIL VARCHAR(50) NOT NULL,
34 | PHONE VARCHAR(15) DEFAULT NULL,
35 | DOB DATE DEFAULT NULL,
36 | GENDER VARCHAR(6) DEFAULT NULL,
37 | BIO LONGTEXT DEFAULT NULL,
38 | PIC BLOB DEFAULT NULL,
39 | ADDR_ID INT(11) DEFAULT NULL,
40 | PRIMARY KEY (TUTOR_ID),
41 | UNIQUE KEY UK_EMAIL (EMAIL),
42 | CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
43 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
44 |
45 |
46 | CREATE TABLE COURSES
47 | (
48 | COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
49 | NAME VARCHAR(100) NOT NULL,
50 | DESCRIPTION VARCHAR(512) DEFAULT NULL,
51 | START_DATE DATE DEFAULT NULL,
52 | END_DATE DATE DEFAULT NULL,
53 | TUTOR_ID INT(11) NOT NULL,
54 | PRIMARY KEY (COURSE_ID),
55 | CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
56 | ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
57 |
58 |
59 | CREATE TABLE COURSE_ENROLLMENT
60 | (
61 | COURSE_ID INT(11) NOT NULL,
62 | STUD_ID INT(11) NOT NULL,
63 | PRIMARY KEY (COURSE_ID,STUD_ID),
64 | CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
65 | CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
66 | ) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
67 |
68 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/sql/drop_tables.sql:
--------------------------------------------------------------------------------
1 |
2 | DROP TABLE IF EXISTS USER_PICS;
3 | DROP TABLE IF EXISTS COURSE_ENROLLMENT;
4 | DROP TABLE IF EXISTS COURSES;
5 | DROP TABLE IF EXISTS TUTORS;
6 | DROP TABLE IF EXISTS STUDENTS;
7 | DROP TABLE IF EXISTS ADDRESSES;
8 |
9 |
--------------------------------------------------------------------------------
/chapter03/src/main/resources/sql/sample_data.sql:
--------------------------------------------------------------------------------
1 |
2 |
3 | --Sample data for table ADDRESSES
4 |
5 | INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
6 | (1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
7 | (2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
8 | (3,'710 N Cable Rd','Lima','OH','45825','Allen'),
9 | (4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
10 |
11 | -- Sample data for table STUDENTS
12 |
13 | INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
14 | (1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
15 | (2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
16 |
17 | -- Sample data for table TUTORS
18 |
19 | INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,GENDER,BIO,PIC,ADDR_ID) VALUES
20 | (1,'John','john@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
21 | (2,'Ken','ken@gmail.com','111-222-3333','1980-05-20','MALE',NULL,NULL,1),
22 | (3,'Paul','paul@gmail.com','123-321-4444','1981-03-15','FEMALE',NULL,NULL,2),
23 | (4,'Mike','mike@gmail.com','123-321-4444','1981-03-15','MALE',NULL,NULL,2);
24 |
25 | -- Sample data for table courses
26 |
27 | INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
28 | (1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
29 | (2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
30 | (3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
31 |
32 | -- Sample data for table COURSE_ENROLLMENT
33 |
34 | INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
35 | (1,1),
36 | (1,2),
37 | (2,2);
38 |
39 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/com/mybatis3/services/CourseServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Date;
5 | import java.util.HashMap;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 | import org.junit.AfterClass;
10 | import org.junit.Assert;
11 | import org.junit.BeforeClass;
12 | import org.junit.Test;
13 |
14 | import com.mybatis3.domain.Course;
15 |
16 | public class CourseServiceTest
17 | {
18 | private static CourseService courseService;
19 |
20 | @BeforeClass
21 | public static void setup()
22 | {
23 | TestDataPopulator.initDatabase();
24 | courseService = new CourseService();
25 | }
26 |
27 | @AfterClass
28 | public static void teardown()
29 | {
30 | courseService = null;
31 | }
32 |
33 | @Test
34 | public void searchCourses()
35 | {
36 | Map map = new HashMap();
37 | map.put("tutorId", 1);
38 | //map.put("courseName", "%java%");
39 | map.put("startDate", new Date());
40 | List courses = courseService.searchCourses(map);
41 | Assert.assertNotNull(courses);
42 | for (Course course : courses) {
43 | Assert.assertNotNull(course);
44 | //System.out.println(course);
45 | }
46 | }
47 |
48 | @Test
49 | public void searchCoursesByTutors()
50 | {
51 | Map map = new HashMap();
52 | List tutorIds = new ArrayList();
53 | tutorIds.add(1);
54 | tutorIds.add(2);
55 | map.put("tutorIds", tutorIds);
56 | map.put("courseName", "%java%");
57 | map.put("startDate", new Date());
58 | List courses = courseService.searchCoursesByTutors(map);
59 | Assert.assertNotNull(courses);
60 | for (Course course : courses) {
61 | Assert.assertNotNull(course);
62 | //System.out.println(course);
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/com/mybatis3/services/StudentServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | import org.junit.AfterClass;
8 | import static org.junit.Assert.*;
9 |
10 | import org.junit.BeforeClass;
11 | import org.junit.Test;
12 |
13 | import com.mybatis3.domain.PhoneNumber;
14 | import com.mybatis3.domain.Student;
15 |
16 |
17 |
18 | public class StudentServiceTest
19 | {
20 | private static StudentService studentService;
21 |
22 | @BeforeClass
23 | public static void setup()
24 | {
25 | studentService = new StudentService();
26 | TestDataPopulator.initDatabase();
27 | }
28 |
29 | @AfterClass
30 | public static void teardown()
31 | {
32 | studentService = null;
33 | }
34 |
35 | @Test
36 | public void testFindAllStudents()
37 | {
38 | List students = studentService.findAllStudents();
39 | assertNotNull(students);
40 | for (Student student : students)
41 | {
42 | assertNotNull(student);
43 | //System.out.println(student);
44 | }
45 |
46 | }
47 |
48 | @Test
49 | public void testFindStudentById()
50 | {
51 | Student student = studentService.findStudentById(1);
52 | assertNotNull(student);
53 | System.out.println(student);
54 | }
55 |
56 | @Test
57 | public void testFindStudentWithAddressById()
58 | {
59 | Student student = studentService.findStudentWithAddressById(1);
60 | assertNotNull(student);
61 | System.out.println(student);
62 | }
63 |
64 | @Test
65 | public void testCreateStudent()
66 | {
67 | Student stud = new Student();
68 | long ts = System.currentTimeMillis();
69 | stud.setName("stud_"+ts);
70 | stud.setEmail("stud_"+ts+"@gmail.com");
71 | stud.setPhone(new PhoneNumber("123-456-7890"));
72 | Student student = studentService.createStudent(stud);
73 | assertNotNull(student);
74 | assertEquals("stud_"+ts, student.getName());
75 | assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
76 | System.out.println("Created Student:"+student);
77 |
78 | }
79 |
80 | @Test
81 | public void testCreateStudentWithMap()
82 | {
83 | Map studMap = new HashMap();
84 | long ts = System.currentTimeMillis();
85 | studMap.put("name","stud_"+ts);
86 | studMap.put("email","stud_"+ts+"@gmail.com");
87 | studMap.put("phone",null);
88 | studentService.createStudentWithMap(studMap);
89 | }
90 |
91 | @Test
92 | public void testUpdateStudent()
93 | {
94 | Student stud = new Student();
95 | long ts = System.currentTimeMillis();
96 | stud.setStudId(2);
97 | stud.setName("stud_"+ts);
98 | stud.setEmail("stud_"+ts+"@gmail.com");
99 | Student updatedStudent = studentService.updateStudent(stud);
100 | assertNotNull(updatedStudent);
101 | assertEquals("stud_"+ts, updatedStudent.getName());
102 | assertEquals("stud_"+ts+"@gmail.com", updatedStudent.getEmail());
103 |
104 | }
105 |
106 | @Test
107 | public void testDeleteStudent()
108 | {
109 | boolean deleteStudent = studentService.deleteStudent(3);
110 | assertTrue(deleteStudent);
111 | System.out.println("deleteStudent:"+deleteStudent);
112 | }
113 |
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/com/mybatis3/services/TestDataPopulator.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.services;
5 |
6 | import java.io.Reader;
7 | import java.sql.Connection;
8 |
9 | import org.apache.ibatis.io.Resources;
10 | import org.apache.ibatis.jdbc.ScriptRunner;
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | import com.mybatis3.util.MyBatisUtil;;
15 |
16 |
17 | /**
18 | * @author Siva
19 | *
20 | */
21 | public class TestDataPopulator
22 | {
23 | private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
24 |
25 | public static void main(String[] args) {
26 | initDatabase();
27 | }
28 |
29 | public static void initDatabase()
30 | {
31 | Connection connection = null;
32 | Reader reader = null;
33 | try {
34 | connection = MyBatisUtil.getConnection();
35 | ScriptRunner scriptRunner = new ScriptRunner(connection);
36 | reader = Resources.getResourceAsReader("sql/drop_tables.sql");
37 | scriptRunner.runScript(reader);
38 | logger.info("drop_tables.sql executed successfully");
39 | reader = Resources.getResourceAsReader("sql/create_tables.sql");
40 | scriptRunner.runScript(reader );
41 | logger.info("create_tables.sql executed successfully");
42 | reader = Resources.getResourceAsReader("sql/sample_data.sql");
43 | scriptRunner.runScript(reader );
44 | logger.info("sample_data.sql executed successfully");
45 | connection.commit();
46 | reader.close();
47 | scriptRunner.closeConnection();
48 | } catch (Exception e) {
49 | throw new RuntimeException(e);
50 | }
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/com/mybatis3/services/TutorServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.services;
2 |
3 | import java.util.List;
4 |
5 | import org.junit.AfterClass;
6 | import org.junit.Assert;
7 | import org.junit.BeforeClass;
8 | import org.junit.Test;
9 |
10 | import com.mybatis3.domain.Course;
11 | import com.mybatis3.domain.Tutor;
12 |
13 |
14 |
15 | public class TutorServiceTest
16 | {
17 | private static TutorService tutorService;
18 |
19 | @BeforeClass
20 | public static void setup()
21 | {
22 | TestDataPopulator.initDatabase();
23 | tutorService = new TutorService();
24 | }
25 |
26 | @AfterClass
27 | public static void teardown()
28 | {
29 | tutorService = null;
30 | }
31 |
32 |
33 | @Test
34 | public void testFindTutorById() {
35 | Tutor tutor = tutorService.findTutorById(1);
36 | Assert.assertNotNull(tutor);
37 | List courses = tutor.getCourses();
38 | Assert.assertNotNull(courses);
39 | for (Course course : courses)
40 | {
41 | Assert.assertNotNull(course);
42 | System.out.println(course);
43 | }
44 | }
45 |
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/chapter04/README.txt:
--------------------------------------------------------------------------------
1 | Chapter 4: SQL Mappers using Annotations
2 | ========================================
3 | This chapter describes mapping SQL statements and query results to java beans in SQL Mappers using Annotation based approach.
4 | Topics covered:
5 | • CRUD Mapping
6 | • ResultSet Mapping
7 | • One-To-One, One-To-Many mappings
8 | • Dynamic SQL mapping
9 |
10 | How to Run:
11 | Update the database properties in application.properties file.
12 | You can run the JUnit tests in src/test/java folder.
13 | In JUnit Tests we have Database Initialization logic to setup sample data.
14 |
15 | public class StudentServiceTest
16 | {
17 | @BeforeClass
18 | public static void setup() {
19 | studentService = new StudentService();
20 | TestDataPopulator.initDatabase(); // this will drop and re-create database and populates sample data.
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/chapter04/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.mybatis3
8 | chapter04
9 | 0.0.1
10 | jar
11 |
12 | chapter04
13 | http://www.mybatis.org
14 | MyBatis Book Chapter 04
15 |
16 |
17 | UTF-8
18 | 1.6
19 | 4.11
20 | 1.7.5
21 | 1.2.17
22 | 3.2.2
23 | 5.1.21
24 | 2.3.2
25 |
26 |
27 |
28 | ${project.artifactId}
29 |
30 |
31 | org.apache.maven.plugins
32 | maven-compiler-plugin
33 | ${maven.compiler.plugin}
34 |
35 | ${java.version}
36 | ${java.version}
37 | ${project.build.sourceEncoding}
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | junit
48 | junit
49 | ${junit.version}
50 | test
51 |
52 |
53 |
54 | org.mybatis
55 | mybatis
56 | ${mybatis.version}
57 |
58 |
59 |
60 | org.slf4j
61 | slf4j-api
62 | ${slf4j.version}
63 |
64 |
65 |
66 | org.slf4j
67 | slf4j-log4j12
68 | ${slf4j.version}
69 | runtime
70 |
71 |
72 |
73 | log4j
74 | log4j
75 | ${log4j.version}
76 | runtime
77 |
78 |
79 |
80 | mysql
81 | mysql-connector-java
82 | ${mysql.version}
83 | runtime
84 |
85 |
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/domain/Address.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * @author Siva
7 | *
8 | */
9 | public class Address implements Serializable
10 | {
11 | private static final long serialVersionUID = 1L;
12 |
13 | private Integer addrId;
14 | private String street;
15 | private String city;
16 | private String state;
17 | private String zip;
18 | private String country;
19 |
20 | @Override
21 | public String toString() {
22 | return "Address [addrId=" + addrId + ", street=" + street + ", city=" + city
23 | + ", state=" + state + ", zip=" + zip + ", country=" + country
24 | + "]";
25 | }
26 | public Address()
27 | {
28 | }
29 | public Address(Integer addrId)
30 | {
31 | this.addrId = addrId;
32 | }
33 | public Address(Integer addrId, String street, String city, String state,
34 | String zip, String country)
35 | {
36 | this.addrId = addrId;
37 | this.street = street;
38 | this.city = city;
39 | this.state = state;
40 | this.zip = zip;
41 | this.country = country;
42 | }
43 | public Integer getAddrId() {
44 | return addrId;
45 | }
46 | public void setAddrId(Integer addrId) {
47 | this.addrId = addrId;
48 | }
49 | public String getStreet()
50 | {
51 | return street;
52 | }
53 | public void setStreet(String street)
54 | {
55 | this.street = street;
56 | }
57 | public String getCity()
58 | {
59 | return city;
60 | }
61 | public void setCity(String city)
62 | {
63 | this.city = city;
64 | }
65 | public String getState()
66 | {
67 | return state;
68 | }
69 | public void setState(String state)
70 | {
71 | this.state = state;
72 | }
73 | public String getZip()
74 | {
75 | return zip;
76 | }
77 | public void setZip(String zip)
78 | {
79 | this.zip = zip;
80 | }
81 | public String getCountry()
82 | {
83 | return country;
84 | }
85 | public void setCountry(String country)
86 | {
87 | this.country = country;
88 | }
89 |
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/domain/Course.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | /**
9 | * @author Siva
10 | *
11 | */
12 | public class Course implements Serializable
13 | {
14 | private static final long serialVersionUID = 1L;
15 |
16 | private Integer courseId;
17 | private String name;
18 | private String description;
19 | private Date startDate;
20 | private Date endDate;
21 | private Tutor tutor;
22 | private List students;
23 |
24 | @Override
25 | public String toString() {
26 | return "Course [courseId=" + courseId + ", name=" + name + ", description="
27 | + description + ", startDate=" + startDate + ", endDate="
28 | + endDate + ", tutor=" + tutor + ", students=" + students + "]";
29 | }
30 | public Integer getCourseId()
31 | {
32 | return courseId;
33 | }
34 | public void setCourseId(Integer id)
35 | {
36 | this.courseId = id;
37 | }
38 | public String getName()
39 | {
40 | return name;
41 | }
42 | public void setName(String name)
43 | {
44 | this.name = name;
45 | }
46 | public String getDescription()
47 | {
48 | return description;
49 | }
50 | public void setDescription(String description)
51 | {
52 | this.description = description;
53 | }
54 | public Date getStartDate()
55 | {
56 | return startDate;
57 | }
58 | public void setStartDate(Date startDate)
59 | {
60 | this.startDate = startDate;
61 | }
62 | public Date getEndDate()
63 | {
64 | return endDate;
65 | }
66 | public void setEndDate(Date endDate)
67 | {
68 | this.endDate = endDate;
69 | }
70 | public List getStudents()
71 | {
72 | if(students == null){
73 | students = new ArrayList(0);
74 | }
75 | return students;
76 | }
77 | public void setStudents(List students)
78 | {
79 | this.students = students;
80 | }
81 | public Tutor getTutor() {
82 | return tutor;
83 | }
84 | public void setTutor(Tutor tutor) {
85 | this.tutor = tutor;
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/domain/PhoneNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.domain;
5 |
6 | import java.io.Serializable;
7 |
8 |
9 | /**
10 | * @author Siva
11 | *
12 | */
13 | public class PhoneNumber implements Serializable
14 | {
15 | private static final long serialVersionUID = 1L;
16 |
17 | private String countryCode;
18 | private String stateCode;
19 | private String number;
20 |
21 | public PhoneNumber() {
22 | }
23 |
24 | public PhoneNumber(String countryCode, String stateCode, String number) {
25 | super();
26 | this.countryCode = countryCode;
27 | this.stateCode = stateCode;
28 | this.number = number;
29 | }
30 |
31 | public PhoneNumber(String string) {
32 | if(string != null){
33 | String[] parts = string.split("-");
34 | if(parts.length>0) this.countryCode=parts[0];
35 | if(parts.length>1) this.stateCode=parts[1];
36 | if(parts.length>2) this.number=parts[2];
37 |
38 | }
39 | }
40 |
41 | /*@Override
42 | public String toString() {
43 | return this.getAsString();
44 | }*/
45 |
46 | public String getCountryCode() {
47 | return countryCode;
48 | }
49 |
50 | public void setCountryCode(String countryCode) {
51 | this.countryCode = countryCode;
52 | }
53 |
54 | public String getStateCode() {
55 | return stateCode;
56 | }
57 |
58 | public void setStateCode(String stateCode) {
59 | this.stateCode = stateCode;
60 | }
61 |
62 | public String getNumber() {
63 | return number;
64 | }
65 |
66 | public void setNumber(String number) {
67 | this.number = number;
68 | }
69 |
70 | public String getAsString() {
71 | return countryCode+"-"+stateCode+"-"+number;
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/domain/Student.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 |
5 |
6 | /**
7 | * @author Siva
8 | *
9 | */
10 | public class Student implements Serializable
11 | {
12 | private static final long serialVersionUID = 1L;
13 | private Integer studId;
14 | private String name;
15 | private String email;
16 | private PhoneNumber phone;
17 | private Address address;
18 |
19 | @Override
20 | public String toString() {
21 | return "Student [studId=" + studId + ", name=" + name + ", email=" + email
22 | + ", phone=" + (phone==null?null:phone.getAsString()) + ", address=" + address + "]";
23 | }
24 | public Student()
25 | {
26 | }
27 | public Student(Integer id)
28 | {
29 | this.studId = id;
30 | }
31 | public Integer getStudId()
32 | {
33 | return studId;
34 | }
35 | public void setStudId(Integer id)
36 | {
37 | this.studId = id;
38 | }
39 | public String getName()
40 | {
41 | return name;
42 | }
43 | public void setName(String name)
44 | {
45 | this.name = name;
46 | }
47 | public String getEmail()
48 | {
49 | return email;
50 | }
51 | public void setEmail(String email)
52 | {
53 | this.email = email;
54 | }
55 | public Address getAddress() {
56 | return address;
57 | }
58 | public void setAddress(Address address) {
59 | this.address = address;
60 | }
61 | public PhoneNumber getPhone() {
62 | return phone;
63 | }
64 | public void setPhone(PhoneNumber phone) {
65 | this.phone = phone;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/domain/Tutor.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.domain;
2 |
3 | import java.io.Serializable;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Siva
8 | *
9 | */
10 | public class Tutor implements Serializable
11 | {
12 | private static final long serialVersionUID = 1L;
13 |
14 | private Integer tutorId;
15 | private String name;
16 | private String email;
17 | private Address address;
18 | private List courses;
19 |
20 | @Override
21 | public String toString() {
22 | return "Tutor [tutorId=" + tutorId + ", name=" + name + ", email=" + email
23 | + ", address=" + address + ", courses=" + courses + "]";
24 | }
25 | public Tutor()
26 | {
27 | }
28 | public Tutor(Integer id)
29 | {
30 | this.tutorId = id;
31 | }
32 | public Integer getTutorId()
33 | {
34 | return tutorId;
35 | }
36 | public void setTutorId(Integer id)
37 | {
38 | this.tutorId = id;
39 | }
40 | public String getName()
41 | {
42 | return name;
43 | }
44 | public void setName(String name)
45 | {
46 | this.name = name;
47 | }
48 | public String getEmail()
49 | {
50 | return email;
51 | }
52 | public void setEmail(String email)
53 | {
54 | this.email = email;
55 | }
56 | public Address getAddress()
57 | {
58 | return address;
59 | }
60 | public void setAddress(Address address)
61 | {
62 | this.address = address;
63 | }
64 | public List getCourses() {
65 | return courses;
66 | }
67 | public void setCourses(List courses) {
68 | this.courses = courses;
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/mappers/AddressMapper.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.mybatis3.mappers;
5 |
6 | import org.apache.ibatis.annotations.Select;
7 |
8 | import com.mybatis3.domain.Address;
9 |
10 | /**
11 | * @author Siva
12 | *
13 | */
14 | public interface AddressMapper
15 | {
16 | @Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}")
17 | Address selectAddressById(int id);
18 | }
19 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/com/mybatis3/mappers/StudentMapper.java:
--------------------------------------------------------------------------------
1 | package com.mybatis3.mappers;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | import org.apache.ibatis.annotations.Delete;
7 | import org.apache.ibatis.annotations.Insert;
8 | import org.apache.ibatis.annotations.Options;
9 | import org.apache.ibatis.annotations.Result;
10 | import org.apache.ibatis.annotations.ResultMap;
11 | import org.apache.ibatis.annotations.Results;
12 | import org.apache.ibatis.annotations.Select;
13 | import org.apache.ibatis.annotations.Update;
14 |
15 | import com.mybatis3.domain.Student;
16 |
17 |
18 |
19 | /**
20 | * @author Siva
21 | *
22 | */
23 | public interface StudentMapper
24 | {
25 |
26 | @Select("select * from students")
27 | @Results({
28 | @Result(id=true, column="stud_id", property="studId"),
29 | @Result(column="name", property="name"),
30 | @Result(column="email", property="email"),
31 | @Result(column="addr_id", property="address.addrId")
32 | })
33 | List findAllStudents();
34 |
35 | @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students")
36 | List