├── .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> findAllStudentsMap(); 37 | 38 | @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}") 39 | Student findStudentById(Integer id); 40 | 41 | @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}") 42 | Map findStudentMapById(Integer id); 43 | 44 | @Select("select stud_id, name, email, a.addr_id, street, city, state, zip, country"+ 45 | " FROM students s left outer join addresses a on s.addr_id=a.addr_id"+ 46 | " where stud_id=#{studId} ") 47 | @ResultMap("com.mybatis3.mappers.StudentMapper.StudentWithAddressResult") 48 | Student selectStudentWithAddress(int studId); 49 | 50 | @Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})") 51 | @Options(useGeneratedKeys=true, keyProperty="studId") 52 | void insertStudent(Student student); 53 | 54 | @Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})") 55 | @Options(useGeneratedKeys=true, keyProperty="studId") 56 | void insertStudentWithMap(Map map); 57 | 58 | @Update("update students set name=#{name}, email=#{email}, phone=#{phone} where stud_id=#{studId}") 59 | void updateStudent(Student student); 60 | 61 | @Delete("delete from students where stud_id=#{studId}") 62 | int deleteStudent(int studId); 63 | 64 | } 65 | -------------------------------------------------------------------------------- /chapter04/src/main/java/com/mybatis3/mappers/TutorMapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.mappers; 5 | 6 | import java.util.List; 7 | 8 | import org.apache.ibatis.annotations.DeleteProvider; 9 | import org.apache.ibatis.annotations.InsertProvider; 10 | import org.apache.ibatis.annotations.Many; 11 | import org.apache.ibatis.annotations.One; 12 | import org.apache.ibatis.annotations.Options; 13 | import org.apache.ibatis.annotations.Param; 14 | import org.apache.ibatis.annotations.Result; 15 | import org.apache.ibatis.annotations.ResultMap; 16 | import org.apache.ibatis.annotations.Results; 17 | import org.apache.ibatis.annotations.Select; 18 | import org.apache.ibatis.annotations.SelectProvider; 19 | import org.apache.ibatis.annotations.UpdateProvider; 20 | 21 | import com.mybatis3.domain.Course; 22 | import com.mybatis3.domain.Tutor; 23 | import com.mybatis3.sqlproviders.TutorDynaSqlProvider; 24 | 25 | 26 | /** 27 | * @author Siva 28 | * 29 | */ 30 | 31 | public interface TutorMapper 32 | { 33 | 34 | @Select("select * from courses where tutor_id=#{tutorId}") 35 | @ResultMap("com.mybatis3.mappers.TutorMapper.CourseResult") 36 | List selectCoursesByTutorId(int tutorId); 37 | 38 | @Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tutors t where t.tutor_id=#{tutorId}") 39 | @Results({ 40 | @Result(id=true, column="tutor_id", property="tutorId"), 41 | @Result(column="tutor_name", property="name"), 42 | @Result(column="email", property="email"), 43 | @Result(property="address", column="addr_id", 44 | one=@One(select="com.mybatis3.mappers.AddressMapper.selectAddressById")), 45 | @Result(property="courses", column="tutor_id", 46 | many=@Many(select="com.mybatis3.mappers.TutorMapper.selectCoursesByTutorId")) 47 | }) 48 | Tutor selectTutorWithCoursesById(int tutorId); 49 | 50 | @SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutorsSql") 51 | List findAllTutors(); 52 | 53 | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql") 54 | Tutor findTutorById(int tutorId); 55 | 56 | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNameAndEmailSql") 57 | Tutor findTutorByNameAndEmail(@Param("name")String name, @Param("email")String email); 58 | 59 | @InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor") 60 | @Options(useGeneratedKeys=true, keyProperty="tutorId") 61 | int insertTutor(Tutor tutor); 62 | 63 | @UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor") 64 | int updateTutor(Tutor tutor); 65 | 66 | @DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor") 67 | int deleteTutor(int tutorId); 68 | 69 | @SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorById") 70 | @ResultMap("com.mybatis3.mappers.TutorMapper.TutorResult") 71 | Tutor selectTutorById(int tutorId); 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /chapter04/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 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import com.mybatis3.domain.Student; 11 | import com.mybatis3.mappers.StudentMapper; 12 | import com.mybatis3.util.MyBatisUtil; 13 | 14 | public class StudentService 15 | { 16 | private Logger logger = LoggerFactory.getLogger(getClass()); 17 | 18 | public List findAllStudents() 19 | { 20 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 21 | try { 22 | StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class); 23 | return StudentMapper.findAllStudents(); 24 | } finally { 25 | sqlSession.close(); 26 | } 27 | } 28 | 29 | public Student findStudentById(Integer id) 30 | { 31 | logger.debug("findStudentById :"+id); 32 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 33 | try { 34 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 35 | return studentMapper.findStudentById(id); 36 | } finally { 37 | sqlSession.close(); 38 | } 39 | } 40 | 41 | public Student findStudentWithAddressById(int id) { 42 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 43 | try { 44 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 45 | return studentMapper.selectStudentWithAddress(id); 46 | } finally { 47 | sqlSession.close(); 48 | } 49 | } 50 | 51 | public Student createStudent(Student student) { 52 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 53 | try { 54 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 55 | mapper.insertStudent(student); 56 | sqlSession.commit(); 57 | return student; 58 | } 59 | catch (Exception e) { 60 | sqlSession.rollback(); 61 | e.printStackTrace(); 62 | throw new RuntimeException(e.getCause()); 63 | } 64 | finally { 65 | sqlSession.close(); 66 | } 67 | } 68 | 69 | public void createStudentWithMap(Map studentDataMap) { 70 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 71 | try { 72 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 73 | mapper.insertStudentWithMap(studentDataMap); 74 | sqlSession.commit(); 75 | } 76 | catch (Exception e) { 77 | sqlSession.rollback(); 78 | e.printStackTrace(); 79 | throw new RuntimeException(e.getCause()); 80 | } 81 | finally { 82 | sqlSession.close(); 83 | } 84 | } 85 | 86 | public Student updateStudent(Student student) { 87 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 88 | try { 89 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 90 | mapper.updateStudent(student); 91 | sqlSession.commit(); 92 | return student; 93 | } 94 | catch (Exception e) { 95 | sqlSession.rollback(); 96 | e.printStackTrace(); 97 | throw new RuntimeException(e.getCause()); 98 | } 99 | finally { 100 | sqlSession.close(); 101 | } 102 | } 103 | 104 | public boolean deleteStudent(int id) { 105 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 106 | try { 107 | StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 108 | int count = mapper.deleteStudent(id); 109 | sqlSession.commit(); 110 | return count > 0; 111 | } 112 | catch (Exception e) { 113 | sqlSession.rollback(); 114 | e.printStackTrace(); 115 | throw new RuntimeException(e.getCause()); 116 | } 117 | finally { 118 | sqlSession.close(); 119 | } 120 | } 121 | 122 | public Map findStudentMapById(int id) { 123 | 124 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 125 | try { 126 | StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 127 | return studentMapper.findStudentMapById(id); 128 | } finally { 129 | sqlSession.close(); 130 | } 131 | 132 | } 133 | 134 | public List> findAllStudentsMap() { 135 | 136 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 137 | try { 138 | StudentMapper StudentMapper = sqlSession.getMapper(StudentMapper.class); 139 | return StudentMapper.findAllStudentsMap(); 140 | } finally { 141 | sqlSession.close(); 142 | } 143 | 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /chapter04/src/main/java/com/mybatis3/services/TutorService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.services; 5 | 6 | import java.util.List; 7 | 8 | import org.apache.ibatis.session.SqlSession; 9 | 10 | import com.mybatis3.domain.Tutor; 11 | import com.mybatis3.mappers.TutorMapper; 12 | import com.mybatis3.util.MyBatisUtil; 13 | 14 | 15 | /** 16 | * @author Siva 17 | * 18 | */ 19 | 20 | public class TutorService 21 | { 22 | public List findAllTutors() 23 | { 24 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 25 | try { 26 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 27 | return mapper.findAllTutors(); 28 | } finally { 29 | sqlSession.close(); 30 | } 31 | } 32 | 33 | public Tutor findTutorById(int tutorId) 34 | { 35 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 36 | try { 37 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 38 | return mapper.findTutorById(tutorId); 39 | } finally { 40 | sqlSession.close(); 41 | } 42 | } 43 | 44 | public Tutor findTutorByNameAndEmail(String name, String email) 45 | { 46 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 47 | try { 48 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 49 | return mapper.findTutorByNameAndEmail(name, email); 50 | } finally { 51 | sqlSession.close(); 52 | } 53 | } 54 | 55 | public Tutor createTutor(Tutor tutor) 56 | { 57 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 58 | try { 59 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 60 | mapper.insertTutor(tutor); 61 | sqlSession.commit(); 62 | } finally { 63 | sqlSession.close(); 64 | } 65 | return tutor; 66 | } 67 | 68 | public Tutor updateTutor(Tutor tutor) 69 | { 70 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 71 | try { 72 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 73 | mapper.updateTutor(tutor); 74 | sqlSession.commit(); 75 | } finally { 76 | sqlSession.close(); 77 | } 78 | return tutor; 79 | } 80 | 81 | public boolean deleteTutor(int tutorId) 82 | { 83 | boolean deleted = false; 84 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 85 | try { 86 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 87 | int nor = mapper.deleteTutor(tutorId); 88 | deleted = (nor == 1); 89 | sqlSession.commit(); 90 | } finally { 91 | sqlSession.close(); 92 | } 93 | return deleted; 94 | } 95 | 96 | public Tutor selectTutorById(int tutorId) 97 | { 98 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 99 | try { 100 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 101 | return mapper.selectTutorById(tutorId); 102 | } finally { 103 | sqlSession.close(); 104 | } 105 | } 106 | 107 | public Tutor selectTutorWithCoursesById(int tutorId) { 108 | SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 109 | try { 110 | TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 111 | return mapper.selectTutorWithCoursesById(tutorId); 112 | } 113 | 114 | finally { 115 | sqlSession.close(); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /chapter04/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.sqlproviders; 5 | 6 | 7 | import java.util.Map; 8 | 9 | import org.apache.ibatis.jdbc.SQL; 10 | 11 | import com.mybatis3.domain.Tutor; 12 | /** 13 | * @author Siva 14 | * 15 | */ 16 | public class TutorDynaSqlProvider 17 | { 18 | 19 | public String findAllTutorsSql() 20 | { 21 | return new SQL() {{ 22 | SELECT("tutor_id as tutorId, name, email"); 23 | FROM("tutors"); 24 | }}.toString(); 25 | } 26 | 27 | public String findTutorByIdSql(final int tutorId) 28 | { 29 | /*return new SQL() {{ 30 | SELECT("tutor_id as tutorId, name, email"); 31 | FROM("tutors"); 32 | WHERE("tutor_id = #{tutorId}"); 33 | }}.toString();*/ 34 | 35 | return new SQL() {{ 36 | SELECT("tutor_id as tutorId, name, email"); 37 | FROM("tutors"); 38 | WHERE("tutor_id="+tutorId); 39 | }}.toString(); 40 | } 41 | 42 | 43 | public String findTutorByNameAndEmailSql(Map map) 44 | { 45 | //String name = (String) map.get("name"); 46 | //String email = (String) map.get("email"); 47 | //System.err.println(name+":"+email); 48 | 49 | return new SQL() {{ 50 | SELECT("tutor_id as tutorId, name, email"); 51 | FROM("tutors"); 52 | WHERE("name=#{name} AND email=#{email}"); 53 | }}.toString(); 54 | } 55 | 56 | public String insertTutor(final Tutor tutor) { 57 | 58 | return new SQL() {{ 59 | INSERT_INTO("TUTORS"); 60 | 61 | if (tutor.getName() != null) { 62 | VALUES("NAME", "#{name}"); 63 | } 64 | 65 | if (tutor.getEmail() != null) { 66 | VALUES("EMAIL", "#{email}"); 67 | } 68 | }}.toString(); 69 | 70 | } 71 | 72 | public String updateTutor(final Tutor tutor) 73 | { 74 | 75 | return new SQL() {{ 76 | UPDATE("TUTORS"); 77 | 78 | if (tutor.getName() != null) { 79 | SET("NAME = #{name}"); 80 | } 81 | 82 | if (tutor.getEmail() != null) { 83 | SET("EMAIL = #{email}"); 84 | } 85 | WHERE("TUTOR_ID = #{tutorId}"); 86 | }}.toString(); 87 | } 88 | 89 | public String deleteTutor(int tutorId) 90 | { 91 | 92 | return new SQL() {{ 93 | DELETE_FROM("TUTORS"); 94 | WHERE("TUTOR_ID = #{tutorId}"); 95 | }}.toString(); 96 | 97 | } 98 | 99 | public String selectTutorById() 100 | { 101 | return new SQL() {{ 102 | SELECT("t.tutor_id, t.name as tutor_name, email"); 103 | SELECT("a.addr_id, street, city, state, zip, country"); 104 | SELECT("course_id, c.name as course_name, description, start_date, end_date"); 105 | FROM("TUTORS t"); 106 | LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id"); 107 | LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id"); 108 | WHERE("t.TUTOR_ID = #{id}"); 109 | }}.toString(); 110 | 111 | 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /chapter04/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 | 49 | } 50 | -------------------------------------------------------------------------------- /chapter04/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 SqlSessionFactory sqlSessionFactory; 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 Connection getConnection() 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 | Connection connection = null; 41 | try { 42 | Class.forName(driver); 43 | connection = DriverManager.getConnection(url, username, password); 44 | } catch (Exception e) { 45 | throw new RuntimeException(e); 46 | } 47 | return connection; 48 | } 49 | 50 | public static SqlSessionFactory getSqlSessionFactory() 51 | { 52 | if(sqlSessionFactory==null) 53 | { 54 | InputStream inputStream; 55 | try 56 | { 57 | inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 58 | sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 59 | }catch (IOException e) 60 | { 61 | throw new RuntimeException(e.getCause()); 62 | } 63 | } 64 | return sqlSessionFactory; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /chapter04/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 | -------------------------------------------------------------------------------- /chapter04/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 | -------------------------------------------------------------------------------- /chapter04/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 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /chapter04/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 -------------------------------------------------------------------------------- /chapter04/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 | -------------------------------------------------------------------------------- /chapter04/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 | -------------------------------------------------------------------------------- /chapter04/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 | -------------------------------------------------------------------------------- /chapter04/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,GENDER,BIO,PIC,ADDR_ID) VALUES 14 | (1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25','MALE',NULL,NULL,3), 15 | (2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15','MALE',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 | -------------------------------------------------------------------------------- /chapter04/src/test/java/com/mybatis3/services/StudentServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mybatis3.services; 2 | 3 | import static org.junit.Assert.*; 4 | 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.BeforeClass; 11 | import org.junit.Test; 12 | 13 | import com.mybatis3.domain.PhoneNumber; 14 | import com.mybatis3.domain.Student; 15 | 16 | public class StudentServiceTest 17 | { 18 | 19 | private static StudentService studentService; 20 | 21 | @BeforeClass 22 | public static void setup() { 23 | studentService = new StudentService(); 24 | TestDataPopulator.initDatabase(); 25 | } 26 | 27 | @AfterClass 28 | public static void teardown() { 29 | studentService = null; 30 | } 31 | 32 | @Test 33 | public void testFindAllStudents() { 34 | List students = studentService.findAllStudents(); 35 | assertNotNull(students); 36 | for (Student student : students) 37 | { 38 | System.err.println(student); 39 | } 40 | } 41 | 42 | @Test 43 | public void testFindStudentById() { 44 | Student student = studentService.findStudentById(1); 45 | System.err.println(student); 46 | System.err.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity()); 47 | 48 | } 49 | 50 | @Test 51 | public void testFindStudentWithAddressById() { 52 | Student student = studentService.findStudentWithAddressById(2); 53 | assertNotNull(student); 54 | System.out.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity()); 55 | } 56 | 57 | @Test 58 | public void testCreateStudent() { 59 | Student stud = new Student(); 60 | long ts = System.currentTimeMillis(); 61 | stud.setName("stud_"+ts); 62 | stud.setEmail("stud_"+ts+"@gmail.com"); 63 | stud.setPhone(new PhoneNumber("123-456-7890")); 64 | Student student = studentService.createStudent(stud); 65 | assertNotNull(student); 66 | assertEquals("stud_"+ts, student.getName()); 67 | assertEquals("stud_"+ts+"@gmail.com", student.getEmail()); 68 | System.err.println("CreatedStudent: "+student); 69 | } 70 | 71 | @Test 72 | public void testCreateStudentWithMap() { 73 | Map studMap = new HashMap(); 74 | long ts = System.currentTimeMillis(); 75 | studMap.put("name","stud_"+ts); 76 | studMap.put("email","stud_"+ts+"@gmail.com"); 77 | studMap.put("phone",null); 78 | studentService.createStudentWithMap(studMap); 79 | } 80 | 81 | @Test 82 | public void testUpdateStudent() { 83 | Student stud = new Student(); 84 | long ts = System.currentTimeMillis(); 85 | stud.setStudId(2); 86 | stud.setName("studddd_"+ts); 87 | stud.setEmail("studddd_"+ts+"@gmail.com"); 88 | Student student = studentService.updateStudent(stud); 89 | assertNotNull(student); 90 | assertEquals("studddd_"+ts, student.getName()); 91 | assertEquals("studddd_"+ts+"@gmail.com", student.getEmail()); 92 | assertEquals(new Integer(2), student.getStudId()); 93 | 94 | System.out.println("UpdatedStudent: "+student); 95 | } 96 | 97 | @Test 98 | public void testDeleteStudent() { 99 | boolean deleted = studentService.deleteStudent(3); 100 | assertTrue(deleted); 101 | System.err.println("deleteStudent:"+deleted); 102 | } 103 | 104 | @Test 105 | public void testFindStudentMapById() { 106 | Map studentMap = studentService.findStudentMapById(1); 107 | System.err.println(studentMap); 108 | } 109 | 110 | @Test 111 | public void testFindAllStudentsMap() { 112 | List> studentMapList = studentService.findAllStudentsMap(); 113 | for(Map studentMap : studentMapList) 114 | { 115 | System.out.println("id :"+studentMap.get("id")); 116 | System.out.println("name :"+studentMap.get("name")); 117 | System.out.println("email :"+studentMap.get("email")); 118 | System.out.println("phone :"+studentMap.get("phone")); 119 | } 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /chapter04/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 | * @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 = MyBatisUtil.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 | -------------------------------------------------------------------------------- /chapter04/src/test/java/com/mybatis3/services/TutorServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mybatis3.services; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.List; 6 | 7 | import org.junit.AfterClass; 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | import com.mybatis3.domain.Tutor; 12 | 13 | public class TutorServiceTest 14 | { 15 | 16 | private static TutorService tutorService; 17 | 18 | @BeforeClass 19 | public static void setup() { 20 | tutorService = new TutorService(); 21 | TestDataPopulator.initDatabase(); 22 | } 23 | 24 | @AfterClass 25 | public static void teardown() { 26 | tutorService = null; 27 | } 28 | 29 | @Test 30 | public void testFindAllTutors() { 31 | List tutors = tutorService.findAllTutors(); 32 | assertNotNull(tutors); 33 | for (Tutor tutor : tutors) 34 | { 35 | System.err.println(tutor); 36 | } 37 | } 38 | 39 | @Test 40 | public void testFindTutorById() { 41 | Tutor tutor = tutorService.findTutorById(1); 42 | assertNotNull(tutor); 43 | System.err.println(tutor); 44 | } 45 | 46 | @Test 47 | public void testFindTutorByNameAndEmail() { 48 | Tutor tutor = tutorService.findTutorByNameAndEmail("Paul", "paul@gmail.com"); 49 | assertNotNull(tutor); 50 | System.err.println(tutor); 51 | } 52 | 53 | @Test 54 | public void testCreateTutor() { 55 | Tutor tutor = new Tutor(); 56 | tutor.setName("siva"); 57 | tutor.setEmail("siva@gmail.com"); 58 | tutor = tutorService.createTutor(tutor); 59 | assertNotNull(tutor); 60 | System.err.println(tutor.getTutorId()); 61 | } 62 | 63 | @Test 64 | public void testUpdateTutor() { 65 | Tutor tutor = new Tutor(); 66 | tutor.setTutorId(1); 67 | tutor.setName("sivaprasad"); 68 | tutor.setEmail("sivaprasad@gmail.com"); 69 | tutor = tutorService.updateTutor(tutor); 70 | Tutor updTutor = tutorService.findTutorById(1); 71 | assertNotNull(updTutor); 72 | System.err.println(updTutor); 73 | } 74 | 75 | @Test 76 | public void testDeleteTutor() { 77 | boolean deleted = tutorService.deleteTutor(4); 78 | assertTrue(deleted); 79 | } 80 | 81 | @Test 82 | public void testSelectTutorById() { 83 | Tutor tutor = tutorService.selectTutorById(1); 84 | assertNotNull(tutor); 85 | System.err.println(tutor); 86 | } 87 | 88 | @Test 89 | public void testSelectTutorWithCoursesById() { 90 | Tutor tutor = tutorService.selectTutorWithCoursesById(1); 91 | assertNotNull(tutor); 92 | System.err.println(tutor); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /chapter05/README.txt: -------------------------------------------------------------------------------- 1 | Chapter 5: Integration with Spring 2 | This chapter explains how to integration MyBatis with Spring framework. 3 | Topics covered: 4 | . Configuring MyBatis in Spring ApplicationContext 5 | . Injecting SqlSession and SQL Mappers 6 | . Transaction Management using Spring 7 | 8 | How to Run: 9 | Update the database properties in application.properties file. 10 | You can run the JUnit tests in src/test/java folder. 11 | In JUnit Tests we have Database Initialization logic to setup sample data. 12 | 13 | public class StudentServiceTest 14 | { 15 | @BeforeClass 16 | public static void setup() { 17 | studentService = new StudentService(); 18 | TestDataPopulator.initDatabase(); // this will drop and re-create database and populates sample data. 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter05/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mybatis3 8 | chapter05 9 | 0.0.1 10 | jar 11 | 12 | chapter04 13 | http://www.mybatis.org 14 | MyBatis Book Chapter 05 15 | 16 | 17 | UTF-8 18 | 1.6 19 | 4.11 20 | 1.7.5 21 | 1.2.17 22 | 3.2.2 23 | 1.2.0 24 | 5.1.21 25 | 26 | 3.1.3.RELEASE 27 | 1.6.8 28 | 2.2 29 | 1.4 30 | 1.6 31 | 2.5 32 | 33 | 2.3.2 34 | 35 | 36 | 37 | ${project.artifactId} 38 | 39 | 40 | org.apache.maven.plugins 41 | maven-compiler-plugin 42 | ${maven.compiler.plugin} 43 | 44 | ${java.version} 45 | ${java.version} 46 | ${project.build.sourceEncoding} 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | junit 57 | junit 58 | ${junit.version} 59 | test 60 | 61 | 62 | 63 | org.springframework 64 | spring-context-support 65 | ${spring.version} 66 | 67 | 68 | commons-logging 69 | commons-logging 70 | 71 | 72 | 73 | 74 | 75 | org.springframework 76 | spring-jdbc 77 | ${spring.version} 78 | 79 | 80 | org.springframework 81 | spring-test 82 | ${spring.version} 83 | test 84 | 85 | 86 | 87 | org.aspectj 88 | aspectjrt 89 | ${aspectj.version} 90 | 91 | 92 | org.aspectj 93 | aspectjweaver 94 | ${aspectj.version} 95 | 96 | 97 | 98 | cglib 99 | cglib-nodep 100 | ${cglib.version} 101 | 102 | 103 | 104 | org.mybatis 105 | mybatis 106 | ${mybatis.version} 107 | 108 | 109 | org.mybatis 110 | mybatis-spring 111 | ${mybatis-spring.version} 112 | 113 | 114 | 115 | org.slf4j 116 | slf4j-api 117 | ${slf4j.version} 118 | 119 | 120 | org.slf4j 121 | jcl-over-slf4j 122 | ${slf4j.version} 123 | runtime 124 | 125 | 126 | org.slf4j 127 | slf4j-log4j12 128 | ${slf4j.version} 129 | runtime 130 | 131 | 132 | 133 | log4j 134 | log4j 135 | ${log4j.version} 136 | runtime 137 | 138 | 139 | 140 | mysql 141 | mysql-connector-java 142 | ${mysql.version} 143 | runtime 144 | 145 | 146 | commons-dbcp 147 | commons-dbcp 148 | ${commons.dbcp.version} 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /chapter05/src/main/java/com/mybatis3/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.mybatis3.config; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.context.annotation.Configuration; 5 | /* 6 | import javax.sql.DataSource; 7 | import org.apache.ibatis.datasource.pooled.PooledDataSource; 8 | import org.apache.ibatis.session.SqlSessionFactory; 9 | import org.mybatis.spring.SqlSessionFactoryBean; 10 | import org.springframework.context.annotation.Bean; 11 | */ 12 | /** 13 | * @author Siva 14 | * 15 | */ 16 | @Configuration 17 | @MapperScan(value="com.mybatis3.mappers") 18 | public class AppConfig 19 | { 20 | /* 21 | @Bean 22 | public DataSource dataSource() { 23 | return new PooledDataSource("com.mysql.jdbc.Driver", 24 | "jdbc:mysql://localhost:3306/elearning", 25 | "root", "admin"); 26 | } 27 | 28 | @Bean 29 | public SqlSessionFactory sqlSessionFactory() throws Exception { 30 | SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); 31 | sessionFactory.setDataSource(dataSource()); 32 | return sessionFactory.getObject(); 33 | } 34 | */ 35 | } 36 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/src/main/java/com/mybatis3/mappers/AddressMapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.mappers; 5 | 6 | import org.apache.ibatis.annotations.Insert; 7 | import org.apache.ibatis.annotations.Select; 8 | 9 | import com.mybatis3.domain.Address; 10 | 11 | /** 12 | * @author Siva 13 | * 14 | */ 15 | public interface AddressMapper 16 | { 17 | @Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}") 18 | Address selectAddressById(int id); 19 | 20 | @Insert("insert into addresses(street, city, state, zip, country) values(#{street},#{city},#{state},#{zip},#{country})") 21 | int insertAddress(Address address); 22 | } 23 | -------------------------------------------------------------------------------- /chapter05/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> findAllStudentsMap(); 37 | 38 | @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}") 39 | Student findStudentById(Integer id); 40 | 41 | @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}") 42 | Map findStudentMapById(Integer id); 43 | 44 | @Select("select stud_id, name, email, a.addr_id, street, city, state, zip, country"+ 45 | " FROM students s left outer join addresses a on s.addr_id=a.addr_id"+ 46 | " where stud_id=#{studId} ") 47 | @ResultMap("com.mybatis3.mappers.StudentMapper.StudentWithAddressResult") 48 | Student selectStudentWithAddress(int studId); 49 | 50 | @Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})") 51 | @Options(useGeneratedKeys=true, keyProperty="studId") 52 | void insertStudent(Student student); 53 | 54 | @Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})") 55 | @Options(useGeneratedKeys=true, keyProperty="studId") 56 | void insertStudentWithMap(Map map); 57 | 58 | @Update("update students set name=#{name}, email=#{email}, phone=#{phone} where stud_id=#{studId}") 59 | void updateStudent(Student student); 60 | 61 | @Delete("delete from students where stud_id=#{studId}") 62 | int deleteStudent(int studId); 63 | 64 | } 65 | -------------------------------------------------------------------------------- /chapter05/src/main/java/com/mybatis3/mappers/TutorMapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.mappers; 5 | 6 | import java.util.List; 7 | 8 | import org.apache.ibatis.annotations.DeleteProvider; 9 | import org.apache.ibatis.annotations.InsertProvider; 10 | import org.apache.ibatis.annotations.Many; 11 | import org.apache.ibatis.annotations.One; 12 | import org.apache.ibatis.annotations.Options; 13 | import org.apache.ibatis.annotations.Param; 14 | import org.apache.ibatis.annotations.Result; 15 | import org.apache.ibatis.annotations.ResultMap; 16 | import org.apache.ibatis.annotations.Results; 17 | import org.apache.ibatis.annotations.Select; 18 | import org.apache.ibatis.annotations.SelectProvider; 19 | import org.apache.ibatis.annotations.UpdateProvider; 20 | 21 | import com.mybatis3.domain.Course; 22 | import com.mybatis3.domain.Tutor; 23 | import com.mybatis3.sqlproviders.TutorDynaSqlProvider; 24 | 25 | 26 | /** 27 | * @author Siva 28 | * 29 | */ 30 | 31 | public interface TutorMapper 32 | { 33 | 34 | @Select("select * from courses where tutor_id=#{tutorId}") 35 | @ResultMap("com.mybatis3.mappers.TutorMapper.CourseResult") 36 | List selectCoursesByTutorId(int tutorId); 37 | 38 | @Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tutors t where t.tutor_id=#{tutorId}") 39 | @Results({ 40 | @Result(id=true, column="tutor_id", property="tutorId"), 41 | @Result(column="tutor_name", property="name"), 42 | @Result(column="email", property="email"), 43 | @Result(property="address", column="addr_id", 44 | one=@One(select="com.mybatis3.mappers.AddressMapper.selectAddressById")), 45 | @Result(property="courses", column="tutor_id", 46 | many=@Many(select="com.mybatis3.mappers.TutorMapper.selectCoursesByTutorId")) 47 | }) 48 | Tutor selectTutorWithCoursesById(int tutorId); 49 | 50 | @SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutorsSql") 51 | List findAllTutors(); 52 | 53 | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql") 54 | Tutor findTutorById(int tutorId); 55 | 56 | @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNameAndEmailSql") 57 | Tutor findTutorByNameAndEmail(@Param("name")String name, @Param("email")String email); 58 | 59 | @InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor") 60 | @Options(useGeneratedKeys=true, keyProperty="tutorId") 61 | int insertTutor(Tutor tutor); 62 | 63 | @UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor") 64 | int updateTutor(Tutor tutor); 65 | 66 | @DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor") 67 | int deleteTutor(int tutorId); 68 | 69 | @SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorById") 70 | @ResultMap("com.mybatis3.mappers.TutorMapper.TutorResult") 71 | Tutor selectTutorById(int tutorId); 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /chapter05/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.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | import com.mybatis3.domain.Address; 13 | import com.mybatis3.domain.Student; 14 | import com.mybatis3.mappers.AddressMapper; 15 | import com.mybatis3.mappers.StudentMapper; 16 | 17 | 18 | @Service 19 | @Transactional 20 | public class StudentService 21 | { 22 | private Logger logger = LoggerFactory.getLogger(getClass()); 23 | 24 | @Autowired 25 | private StudentMapper studentMapper; 26 | 27 | @Autowired 28 | private AddressMapper addressMapper; 29 | 30 | public List findAllStudents() { 31 | return studentMapper.findAllStudents(); 32 | } 33 | 34 | public Student findStudentById(Integer id) { 35 | logger.debug("findStudentById :"+id); 36 | return studentMapper.findStudentById(id); 37 | } 38 | 39 | public Student findStudentWithAddressById(int id) { 40 | return studentMapper.selectStudentWithAddress(id); 41 | } 42 | 43 | public Student createStudent(Student student) { 44 | Address address = student.getAddress(); 45 | if(address != null){ 46 | addressMapper.insertAddress(address); 47 | } 48 | if(student.getName()==null || student.getName().trim().length()==0){ 49 | throw new RuntimeException("Student Name should not be null"); 50 | } 51 | studentMapper.insertStudent(student); 52 | return student; 53 | } 54 | 55 | public void createStudentWithMap(Map studentDataMap) { 56 | studentMapper.insertStudentWithMap(studentDataMap); 57 | } 58 | 59 | public Student updateStudent(Student student) { 60 | studentMapper.updateStudent(student); 61 | return student; 62 | } 63 | 64 | public boolean deleteStudent(int id) { 65 | int count = studentMapper.deleteStudent(id); 66 | return count > 0; 67 | } 68 | 69 | public Map findStudentMapById(int id) { 70 | return studentMapper.findStudentMapById(id); 71 | } 72 | 73 | public List> findAllStudentsMap() { 74 | return studentMapper.findAllStudentsMap(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /chapter05/src/main/java/com/mybatis3/services/TutorService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.services; 5 | 6 | import java.util.List; 7 | 8 | import org.apache.ibatis.session.SqlSession; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.transaction.annotation.Transactional; 12 | 13 | import com.mybatis3.domain.Tutor; 14 | import com.mybatis3.mappers.TutorMapper; 15 | 16 | 17 | /** 18 | * @author Siva 19 | * 20 | */ 21 | @Service 22 | @Transactional 23 | public class TutorService 24 | { 25 | @Autowired 26 | private SqlSession sqlSession; 27 | 28 | private TutorMapper getTutorMapper(){ 29 | return sqlSession.getMapper(TutorMapper.class); 30 | } 31 | public List findAllTutors() { 32 | return getTutorMapper().findAllTutors(); 33 | } 34 | 35 | public Tutor findTutorById(int tutorId) { 36 | return getTutorMapper().findTutorById(tutorId); 37 | } 38 | 39 | public Tutor findTutorByNameAndEmail(String name, String email) { 40 | return getTutorMapper().findTutorByNameAndEmail(name, email); 41 | } 42 | 43 | public Tutor createTutor(Tutor tutor) { 44 | getTutorMapper().insertTutor(tutor); 45 | return tutor; 46 | } 47 | 48 | public Tutor updateTutor(Tutor tutor) { 49 | getTutorMapper().updateTutor(tutor); 50 | return tutor; 51 | } 52 | 53 | public boolean deleteTutor(int tutorId) { 54 | boolean deleted = false; 55 | int nor = getTutorMapper().deleteTutor(tutorId); 56 | deleted = (nor == 1); 57 | return deleted; 58 | } 59 | 60 | public Tutor selectTutorById(int tutorId) { 61 | return getTutorMapper().selectTutorById(tutorId); 62 | } 63 | 64 | public Tutor selectTutorWithCoursesById(int tutorId) { 65 | return getTutorMapper().selectTutorWithCoursesById(tutorId); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /chapter05/src/main/java/com/mybatis3/sqlproviders/TutorDynaSqlProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.mybatis3.sqlproviders; 5 | 6 | import java.util.Map; 7 | 8 | import org.apache.ibatis.jdbc.SQL; 9 | 10 | import com.mybatis3.domain.Tutor; 11 | /** 12 | * @author Siva 13 | * 14 | */ 15 | public class TutorDynaSqlProvider 16 | { 17 | 18 | public String findAllTutorsSql() 19 | { 20 | return new SQL() {{ 21 | SELECT("tutor_id as tutorId, name, email"); 22 | FROM("tutors"); 23 | }}.toString(); 24 | } 25 | 26 | public String findTutorByIdSql(final int tutorId) 27 | { 28 | return new SQL() {{ 29 | SELECT("tutor_id as tutorId, name, email"); 30 | FROM("tutors"); 31 | WHERE("tutor_id="+tutorId); 32 | }}.toString(); 33 | } 34 | 35 | 36 | public String findTutorByNameAndEmailSql(Map map) 37 | { 38 | //String name = (String) map.get("name"); 39 | //String email = (String) map.get("email"); 40 | //System.err.println(name+":"+email); 41 | return new SQL() {{ 42 | SELECT("tutor_id as tutorId, name, email"); 43 | FROM("tutors"); 44 | WHERE("name=#{name} AND email=#{email}"); 45 | }}.toString(); 46 | } 47 | 48 | public String insertTutor(final Tutor tutor) { 49 | return new SQL() {{ 50 | INSERT_INTO("TUTORS"); 51 | 52 | if (tutor.getName() != null) { 53 | VALUES("NAME", "#{name}"); 54 | } 55 | 56 | if (tutor.getEmail() != null) { 57 | VALUES("EMAIL", "#{email}"); 58 | } 59 | }}.toString(); 60 | } 61 | 62 | public String updateTutor(final Tutor tutor) 63 | { 64 | return new SQL() {{ 65 | UPDATE("TUTORS"); 66 | 67 | if (tutor.getName() != null) { 68 | SET("NAME = #{name}"); 69 | } 70 | 71 | if (tutor.getEmail() != null) { 72 | SET("EMAIL = #{email}"); 73 | } 74 | WHERE("TUTOR_ID = #{tutorId}"); 75 | }}.toString(); 76 | } 77 | 78 | public String deleteTutor(int tutorId) 79 | { 80 | return new SQL() {{ 81 | DELETE_FROM("TUTORS"); 82 | WHERE("TUTOR_ID = #{tutorId}"); 83 | }}.toString(); 84 | } 85 | 86 | public String selectTutorById() 87 | { 88 | return new SQL() {{ 89 | SELECT("t.tutor_id, t.name as tutor_name, email, a.addr_id, street, city, state, zip, country,course_id, c.name as course_name, description, start_date, end_date"); 90 | FROM("TUTORS t"); 91 | LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id"); 92 | LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id"); 93 | WHERE("t.TUTOR_ID = #{tutorId}"); 94 | }}.toString(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /chapter05/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 | 49 | } 50 | -------------------------------------------------------------------------------- /chapter05/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 SqlSessionFactory sqlSessionFactory; 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 Connection getConnection() 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 | Connection connection = null; 41 | try { 42 | Class.forName(driver); 43 | connection = DriverManager.getConnection(url, username, password); 44 | } catch (Exception e) { 45 | throw new RuntimeException(e); 46 | } 47 | return connection; 48 | } 49 | 50 | public static SqlSessionFactory getSqlSessionFactory() 51 | { 52 | if(sqlSessionFactory==null) 53 | { 54 | InputStream inputStream; 55 | try 56 | { 57 | inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 58 | sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 59 | }catch (IOException e) 60 | { 61 | throw new RuntimeException(e.getCause()); 62 | } 63 | } 64 | return sqlSessionFactory; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/src/main/resources/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /chapter05/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 -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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 | -------------------------------------------------------------------------------- /chapter05/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,GENDER,BIO,PIC,ADDR_ID) VALUES 14 | (1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25','MALE',NULL,NULL,3), 15 | (2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15','MALE',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 | -------------------------------------------------------------------------------- /chapter05/src/test/java/com/mybatis3/services/StudentServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mybatis3.services; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import org.junit.BeforeClass; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.dao.DataAccessException; 14 | import org.springframework.test.context.ContextConfiguration; 15 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 16 | 17 | import com.mybatis3.domain.Address; 18 | import com.mybatis3.domain.PhoneNumber; 19 | import com.mybatis3.domain.Student; 20 | 21 | @RunWith(SpringJUnit4ClassRunner.class) 22 | @ContextConfiguration(locations="classpath:applicationContext.xml") 23 | public class StudentServiceTest 24 | { 25 | @Autowired 26 | private StudentService studentService; 27 | 28 | @BeforeClass 29 | public static void setup() { 30 | TestDataPopulator.initDatabase(); 31 | } 32 | 33 | @Test 34 | public void testFindAllStudents() { 35 | List students = studentService.findAllStudents(); 36 | assertNotNull(students); 37 | for (Student student : students) 38 | { 39 | System.err.println(student); 40 | } 41 | } 42 | 43 | @Test 44 | public void testFindStudentById() { 45 | Student student = studentService.findStudentById(1); 46 | System.err.println(student); 47 | System.err.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity()); 48 | 49 | } 50 | 51 | @Test 52 | public void testFindStudentWithAddressById() { 53 | Student student = studentService.findStudentWithAddressById(2); 54 | assertNotNull(student); 55 | System.out.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity()); 56 | } 57 | 58 | @Test 59 | public void testCreateStudent() { 60 | //Address address = new Address(); 61 | Address address = new Address(1,"Quaker Ridge Rd.","Bethel","Brooklyn","06801","USA"); 62 | /*address.setStreet("Quaker Ridge Rd."); 63 | address.setCity("Bethel"); 64 | address.setState("Brooklyn"); 65 | address.setZip("06801"); 66 | address.setCountry("USA");*/ 67 | 68 | Student stud = new Student(); 69 | long ts = System.currentTimeMillis(); 70 | stud.setName("stud_"+ts); 71 | stud.setEmail("stud_"+ts+"@gmail.com"); 72 | stud.setPhone(new PhoneNumber("123-456-7890")); 73 | stud.setAddress(address); 74 | Student student = studentService.createStudent(stud); 75 | assertNotNull(student); 76 | assertEquals("stud_"+ts, student.getName()); 77 | assertEquals("stud_"+ts+"@gmail.com", student.getEmail()); 78 | System.err.println("CreatedStudent: "+student); 79 | } 80 | 81 | @Test(expected=DataAccessException.class) 82 | public void testCreateStudentForException() { 83 | Address address = new Address(); 84 | address.setStreet("Quaker Ridge Rd."); 85 | address.setCity("Bethel"); 86 | address.setState("Brooklyn"); 87 | address.setZip("06801"); 88 | address.setCountry("USA"); 89 | 90 | Student stud = new Student(); 91 | long ts = System.currentTimeMillis(); 92 | stud.setName("stud_"+ts); 93 | stud.setEmail("timothy@gmail.com"); 94 | stud.setPhone(new PhoneNumber("123-456-7890")); 95 | stud.setAddress(address); 96 | studentService.createStudent(stud); 97 | fail("You should not reach here"); 98 | } 99 | 100 | @Test 101 | public void testCreateStudentWithMap() { 102 | Map studMap = new HashMap(); 103 | long ts = System.currentTimeMillis(); 104 | studMap.put("name","stud_"+ts); 105 | studMap.put("email","stud_"+ts+"@gmail.com"); 106 | studMap.put("phone",null); 107 | studentService.createStudentWithMap(studMap); 108 | } 109 | 110 | @Test 111 | public void testUpdateStudent() { 112 | Student stud = new Student(); 113 | long ts = System.currentTimeMillis(); 114 | stud.setStudId(2); 115 | stud.setName("studddd_"+ts); 116 | stud.setEmail("studddd_"+ts+"@gmail.com"); 117 | Student student = studentService.updateStudent(stud); 118 | assertNotNull(student); 119 | assertEquals("studddd_"+ts, student.getName()); 120 | assertEquals("studddd_"+ts+"@gmail.com", student.getEmail()); 121 | assertEquals(new Integer(2), student.getStudId()); 122 | 123 | System.out.println("UpdatedStudent: "+student); 124 | } 125 | 126 | @Test 127 | public void testDeleteStudent() { 128 | boolean deleted = studentService.deleteStudent(3); 129 | assertTrue(deleted); 130 | System.err.println("deleteStudent:"+deleted); 131 | } 132 | 133 | @Test 134 | public void testFindStudentMapById() { 135 | Map studentMap = studentService.findStudentMapById(1); 136 | System.err.println(studentMap); 137 | } 138 | 139 | @Test 140 | public void testFindAllStudentsMap() { 141 | List> studentMapList = studentService.findAllStudentsMap(); 142 | for(Map studentMap : studentMapList) 143 | { 144 | System.out.println("id :"+studentMap.get("id")); 145 | System.out.println("name :"+studentMap.get("name")); 146 | System.out.println("email :"+studentMap.get("email")); 147 | System.out.println("phone :"+studentMap.get("phone")); 148 | } 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /chapter05/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 | * @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 = MyBatisUtil.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 | -------------------------------------------------------------------------------- /chapter05/src/test/java/com/mybatis3/services/TutorServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mybatis3.services; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.List; 6 | 7 | import org.junit.BeforeClass; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.test.context.ContextConfiguration; 12 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 13 | 14 | import com.mybatis3.domain.Tutor; 15 | 16 | @RunWith(SpringJUnit4ClassRunner.class) 17 | @ContextConfiguration(locations="classpath:applicationContext.xml") 18 | public class TutorServiceTest 19 | { 20 | @Autowired 21 | private TutorService tutorService; 22 | 23 | @BeforeClass 24 | public static void setup() { 25 | TestDataPopulator.initDatabase(); 26 | } 27 | 28 | 29 | @Test 30 | public void testFindAllTutors() { 31 | List tutors = tutorService.findAllTutors(); 32 | assertNotNull(tutors); 33 | for (Tutor tutor : tutors) 34 | { 35 | System.err.println(tutor); 36 | } 37 | } 38 | 39 | @Test 40 | public void testFindTutorById() { 41 | Tutor tutor = tutorService.findTutorById(1); 42 | assertNotNull(tutor); 43 | //System.err.println(tutor); 44 | } 45 | 46 | @Test 47 | public void testFindTutorByNameAndEmail() { 48 | Tutor tutor = tutorService.findTutorByNameAndEmail("Paul", "paul@gmail.com"); 49 | assertNotNull(tutor); 50 | //System.err.println(tutor); 51 | } 52 | 53 | @Test 54 | public void testCreateTutor() { 55 | Tutor tutor = new Tutor(); 56 | tutor.setName("siva"); 57 | tutor.setEmail("siva@gmail.com"); 58 | tutor = tutorService.createTutor(tutor); 59 | assertNotNull(tutor); 60 | } 61 | 62 | @Test 63 | public void testUpdateTutor() { 64 | Tutor tutor = new Tutor(); 65 | tutor.setTutorId(1); 66 | tutor.setName("sivaprasad"); 67 | tutor.setEmail("sivaprasad@gmail.com"); 68 | tutor = tutorService.updateTutor(tutor); 69 | Tutor updTutor = tutorService.findTutorById(1); 70 | assertNotNull(updTutor); 71 | System.err.println(updTutor); 72 | } 73 | 74 | @Test 75 | public void testDeleteTutor() { 76 | boolean deleted = tutorService.deleteTutor(4); 77 | assertTrue(deleted); 78 | } 79 | 80 | @Test 81 | public void testSelectTutorById() { 82 | Tutor tutor = tutorService.selectTutorById(1); 83 | assertNotNull(tutor); 84 | System.err.println(tutor); 85 | } 86 | 87 | @Test 88 | public void testSelectTutorWithCoursesById() { 89 | Tutor tutor = tutorService.selectTutorWithCoursesById(1); 90 | assertNotNull(tutor); 91 | System.err.println(tutor); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /elearning/README.txt: -------------------------------------------------------------------------------- 1 | This module demonstrate developing a simple web app using MyBatis persistence framework. -------------------------------------------------------------------------------- /elearning/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mybatis3 8 | 0.0.1 9 | elearning 10 | war 11 | E-Learning Webapp 12 | http://maven.apache.org 13 | 14 | UTF-8 15 | 1.6 16 | 4.8.2 17 | 1.6.2 18 | 1.0.1 19 | 1.2.16 20 | 21 | 3.1.0.RELEASE 22 | 3.2.2 23 | 1.2.0 24 | 1.0.0 25 | 26 | 1.6.8 27 | 2.2 28 | 5.1.18 29 | 30 | 1.4 31 | 1.6 32 | 2.5 33 | 34 | 2.5 35 | 2.1 36 | 1.2 37 | 1.1.2 38 | 39 | 2.3.2 40 | 2.4.3-alpha-1 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.mybatis 48 | mybatis-spring 49 | 50 | 51 | 52 | mysql 53 | mysql-connector-java 54 | runtime 55 | 56 | 57 | 58 | org.slf4j 59 | slf4j-api 60 | 61 | 62 | 63 | org.slf4j 64 | slf4j-log4j12 65 | runtime 66 | 67 | 68 | 69 | log4j 70 | log4j 71 | runtime 72 | 73 | 74 | 75 | junit 76 | junit 77 | test 78 | 79 | 80 | 81 | 82 | 83 | ${project.artifactId} 84 | 85 | 86 | org.apache.maven.plugins 87 | maven-compiler-plugin 88 | ${maven.compiler.plugin} 89 | 90 | ${java.version} 91 | ${java.version} 92 | ${project.build.sourceEncoding} 93 | 94 | 95 | 96 | org.codehaus.mojo 97 | failsafe-maven-plugin 98 | ${maven.failsafe.plugin} 99 | 100 | 101 | 102 | integration-test 103 | verify 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | junit 117 | junit 118 | ${junit.version} 119 | test 120 | 121 | 122 | 123 | org.slf4j 124 | slf4j-api 125 | ${slf4j.version} 126 | 127 | 128 | org.slf4j 129 | jcl-over-slf4j 130 | ${slf4j.version} 131 | runtime 132 | 133 | 134 | 135 | org.slf4j 136 | slf4j-log4j12 137 | ${slf4j.version} 138 | runtime 139 | 140 | 141 | 142 | log4j 143 | log4j 144 | ${log4j.version} 145 | runtime 146 | 147 | 148 | 149 | 150 | 151 | org.springframework 152 | spring-context-support 153 | ${spring.version} 154 | 155 | 156 | commons-logging 157 | commons-logging 158 | 159 | 160 | 161 | 162 | 163 | org.springframework 164 | spring-orm 165 | ${spring.version} 166 | 167 | 168 | 169 | org.springframework 170 | spring-web 171 | ${spring.version} 172 | 173 | 174 | org.springframework 175 | spring-webmvc 176 | ${spring.version} 177 | 178 | 179 | org.springframework 180 | spring-test 181 | ${spring.version} 182 | test 183 | 184 | 185 | 186 | org.aspectj 187 | aspectjrt 188 | ${aspectj.version} 189 | 190 | 191 | org.aspectj 192 | aspectjweaver 193 | ${aspectj.version} 194 | 195 | 196 | 197 | cglib 198 | cglib-nodep 199 | ${cglib.version} 200 | 201 | 202 | 203 | 204 | org.mybatis 205 | mybatis 206 | ${mybatis.version} 207 | 208 | 209 | org.mybatis 210 | mybatis-spring 211 | ${mybatis-spring.version} 212 | 213 | 214 | 215 | org.mybatis 216 | mybatis-ehcache 217 | 1.0.0 218 | 219 | 220 | 221 | commons-dbcp 222 | commons-dbcp 223 | ${commons.dbcp.version} 224 | 225 | 226 | 227 | commons-lang 228 | commons-lang 229 | ${commons.lang.version} 230 | 231 | 232 | 233 | commons-pool 234 | commons-pool 235 | ${commons.pool.version} 236 | 237 | 238 | 239 | mysql 240 | mysql-connector-java 241 | ${mysql.version} 242 | runtime 243 | 244 | 245 | 246 | javax.servlet 247 | servlet-api 248 | ${servlet.version} 249 | provided 250 | 251 | 252 | 253 | javax.servlet.jsp 254 | jsp-api 255 | ${jsp.version} 256 | provided 257 | 258 | 259 | 260 | taglibs 261 | standard 262 | ${taglibs-standard.version} 263 | 264 | 265 | 266 | javax.servlet 267 | jstl 268 | ${jstl.version} 269 | 270 | 271 | 272 | opensymphony 273 | sitemesh 274 | 2.4.2 275 | 276 | 277 | 278 | 279 | 280 | 281 | -------------------------------------------------------------------------------- /elearning/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.appender.file=org.apache.log4j.RollingFileAppender 8 | log4j.appender.file.File=mybatisapp.log 9 | log4j.appender.R.MaxFileSize=100KB 10 | # Keep one backup file 11 | log4j.appender.R.MaxBackupIndex=10 12 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 13 | log4j.appender.file.layout.ConversionPattern=%d [%-5p] %c - %m%n 14 | 15 | log4j.logger.chapter02=DEBUG -------------------------------------------------------------------------------- /elearning/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | Archetype Created Web Application 7 | 8 | -------------------------------------------------------------------------------- /elearning/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Hello World!

4 | 5 | 6 | --------------------------------------------------------------------------------