JavaPersistenceWithMyBatis3笔记-第2章Bootstrapping MyBatis-001XMl形式和Java形式

一、

1.Mapper

同上

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5   
 6 <mapper namespace="com.mybatis3.mappers.StudentMapper">
 7     
 8     <resultMap type="Student" id="StudentResult">
 9         <id     property="studId" column="stud_id"/>
10         <result property="name" column="name"/>
11         <result property="email" column="email"/>
12         <result property="dob" column="dob"/>
13     </resultMap>
14   
15       <select id="findAllStudents" resultMap="StudentResult">
16         select * from Students
17       </select>
18       
19       <select id="findStudentById" parameterType="int" resultType="Student">
20         select stud_id as studId, name, email, dob from Students where stud_id=#{studId}
21       </select>
22       
23       <insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
24           INSERT INTO STUDENTS(NAME,EMAIL,DOB) VALUES(#{name},#{email},#{dob})
25       </insert>
26       
27       <update id="updateStudent" parameterType="Student">
28           UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
29       </update>
30       
31 </mapper>

 

2.Service

同上

3.Domain

 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 }

 

 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 }

 

4.TypeHandler

 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<PhoneNumber>{
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 }

 

5.辅助类

 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 }

 

 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 }

 

6.配置及资源文件

(1)mybatis-config.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 
 7     <properties resource="application.properties">
 8         <property name="jdbc.username" value="root"/>
 9           <property name="jdbc.password" value="verysecurepwd"/>    
10     </properties>
11     
12     <!-- <settings>
13        <setting name="cacheEnabled" value="true"/>
14         <setting name="lazyLoadingEnabled" value="true"/>
15         <setting name="multipleResultSetsEnabled" value="true"/>
16         <setting name="useColumnLabel" value="true"/>
17         <setting name="useGeneratedKeys" value="false"/>
18         <setting name="autoMappingBehavior" value="PARTIAL"/>
19         <setting name="defaultExecutorType" value="SIMPLE"/>
20         <setting name="defaultStatementTimeout" value="25000"/>
21         <setting name="safeRowBoundsEnabled" value="false"/>
22         <setting name="mapUnderscoreToCamelCase" value="false"/>
23         <setting name="localCacheScope" value="SESSION"/>
24         <setting name="jdbcTypeForNull" value="OTHER"/>
25         <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
26     </settings> -->
27 
28       <typeAliases>
29           <package name="com.mybatis3.domain"/>
30       </typeAliases>
31     
32       <environments default="development">
33         <environment id="development">
34           <transactionManager type="JDBC"/>
35           <dataSource type="POOLED">
36             <property name="driver" value="${jdbc.driverClassName}"/>
37             <property name="url" value="${jdbc.url}"/>
38             <property name="username" value="${jdbc.username}"/>
39             <property name="password" value="${jdbc.password}"/>
40           </dataSource>
41         </environment>
42       </environments>
43       
44       <mappers>
45         <mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
46         <!-- <package name="com.mybatis3.mappers"/> -->
47       </mappers>
48       
49 </configuration>

 

(2)full-mybatis-config.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 
 7     <!--  This file is for a reference purpose for various configuration options -->
 8     <properties resource="application.properties">
 9         <property name="username" value="db_user"/>
10           <property name="password" value="verysecurepwd"/>    
11     </properties>
12     
13     <settings>
14           <setting name="cacheEnabled" value="true"/>
15           <setting name="lazyLoadingEnabled" value="true"/>
16           <setting name="multipleResultSetsEnabled" value="true"/>
17           <setting name="useColumnLabel" value="true"/>
18           <setting name="useGeneratedKeys" value="false"/>
19           <setting name="autoMappingBehavior" value="PARTIAL"/>
20           <setting name="defaultExecutorType" value="SIMPLE"/>
21           <setting name="defaultStatementTimeout" value="25000"/>
22           <setting name="safeRowBoundsEnabled" value="false"/>
23           <setting name="mapUnderscoreToCamelCase" value="false"/>
24           <setting name="localCacheScope" value="SESSION"/>
25           <setting name="jdbcTypeForNull" value="OTHER"/>
26           <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
27     </settings>
28     
29       <typeAliases>
30           <typeAlias alias="Tutor" type="com.mybatis3.domain.Tutor"/>
31           <package name="com.mybatis3.domain"/>
32       </typeAliases>
33       
34         <typeHandlers>
35           <typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/>
36           <package name="com.mybatis3.typehandlers"/>
37         </typeHandlers>
38 
39      <environments default="development">
40         <environment id="development">
41           <transactionManager type="JDBC"/>
42           <dataSource type="POOLED">
43             <property name="driver" value="${jdbc.driverClassName}"/>
44             <property name="url" value="${jdbc.url}"/>
45             <property name="username" value="${jdbc.username}"/>
46             <property name="password" value="${jdbc.password}"/>
47           </dataSource>
48         </environment>
49         
50         <environment id="production">
51           <transactionManager type="JDBC"/>
52           <dataSource type="JNDI">
53             <property name="data_source" value="java:comp/jdbc/MyBatisDemoDS"/>
54           </dataSource>
55         </environment>
56         
57       </environments>
58       
59       <mappers>
60         <mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
61         <mapper url="file:///var/mappers/StudentMapper.xml"/>
62         <mapper class="com.mybatis3.mappers.TutorMapper"/>
63       </mappers>
64       
65       
66 </configuration>

 

7.测试文件

 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<Student> 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 }

 

posted @ 2016-04-27 19:32  shamgod  阅读(247)  评论(0编辑  收藏  举报
haha