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 }
时间: 2024-10-05 05:01:57

JavaPersistenceWithMyBatis3笔记-第2章Bootstrapping MyBatis-001XMl形式和Java形式的相关文章

JavaPersistenceWithMyBatis3笔记-第4章SQL Mappers Using Annotations-001

一. 1.Mapper 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_i

SQL Server2012 T-SQL基础教程--读书笔记(5-7章)

SQL Server2012 T-SQL基础教程--读书笔记(5-7章) SqlServer T-SQL 示例数据库:点我 Chapter 05 表表达式 5.1 派生表 5.1.1 分配列别名 5.1.2 使用参数 5.1.3 嵌套 5.1.4 多个引用 5.2 公用表表达式 5.2.1 分别列别名 5.2.2 使用参数 5.2.3 定义多个CTE 5.2.4 CTE的多次引用 5.2.5 递归CTE 5.3 视图 5.3.1 视图和ORDER BY 子句 5.3.2 视图选项 5.4 内嵌表

【算法导论】学习笔记——第6章 堆排序

堆这个数据结构应用非常广泛,数字图像处理的算法里也见过.似乎记得以前老师上课说需要用树结构实现堆排序,看了一下算法导论才明白其精髓.堆虽然是一棵树,但显然没必要非得用树结构实现堆排序.堆排序的性质很好,算法时间复杂度为O(nlgn). 1. 堆排序的简要说明.二叉堆可以分为两种形式:最大堆和最小堆.在最大堆中,最大堆性质是指除了根以外的所有结点i都要满足: A[PARENT(i)] >= A[i]:在最小堆中,最小堆性质是指除了根以外的所有结点i都要满足: A[PARENT(i)] <= A[

java JDK8 学习笔记——第16章 整合数据库

第十六章 整合数据库 16.1 JDBC入门 16.1.1 JDBC简介 1.JDBC是java联机数据库的标准规范.它定义了一组标准类与接口,标准API中的接口会有数据库厂商操作,称为JDBC驱动程序. 2.JDBC标准主要分为两个部分:JDBC应用程序开发者接口和JDBC驱动程序开发者接口.应用程序需要联机数据库,其相关API主要在java.sql和javax.sql两个包中. 3.应用程序使用JDBC联机数据库的通用语法: Connection conn = DriverManager.g

《Unix环境高级编程》读书笔记 第7章-进程环境

1. main函数 int main( int argc, char *argv[] ); argc是命令行参数的数目,包括程序名在内 argv是指向参数的各个指针所构成的数组,即指针数组 当内核执行C程序时(使用exec函数),在调用main前先调用一个特殊的启动例程.可执行程序文件将此启动例程指定为程序的起始地址——这是由连接器设置的,而连接器则是由C编译器调用.启动例程从内核取得命令行参数和环境变量值,然后按上述方式调用main函数做好安排. 2. 进程终止 有8种方式使进程终止,其中5种

APUE学习笔记:第九章 进程关系

9.1 引言 本章将更详尽地说明进程组以及POSIX.1引入的会话的概念.还将介绍登陆shell(登录时所调用的)和所有从登陆shell启动的进程之间的关系. 9.1 终端登陆 系统管理员创建通常名为/etc/ttys的文件,其中每个终端设备都有一行,每一行说明设备名传递给getty程序的参数.当系统自举时,内核创建进程ID为1的进程,依旧是init进程.init进程使系统进入多用户状态.init进程读文件/etc/ttys,对每一个允许登陆的终端设备,init调用一次fork,所生成的子进程则

C++PRIMER 阅读笔记 第三章

本章主要介绍 string vector 和 bitset, 不能贪多,现在本文主要介绍 string 与 vector 头文件中最好不要使用namespace std, 因为头文件会直接被预处理器放置到C中 std::string 的构造方式: string s1; string s2(s1); string s3("value");string s4(n,'c');           第三种构造方式可有"\0"? cout 与 cin 可以直接操作string

MySQL Cookbook读书笔记第三章

1,查询指定列/从指定列中查询 若需要指定每一列在查询结果中出现的先后顺序,可以在select语句中指定(dstuser在dsthost之后): 查询显示用户所关注的列: 2,指定查询行 使用where关键字可以查询符合条件限制的数据例如:查找srchost为venus或者srchost以s开头的行记录: 使用操作符like进行模式匹配,其中%表示通配符,代表一个差多为任意值的字符串. where使用操作符and可以查询多个条件: 条件并集: 3,格式化显示查询结果 当查询语句中没有重命名列名,

iOS开发中的那些的约定俗成(1)————《编写高质量iOS与OS X代码的52个有效方法》读书笔记(第一章)

iOS开发中的那些的约定俗成(1) ----<编写高质量iOS与OS X代码的52个有效方法>读书笔记(第一章) 前言 "我要成为一个高产的开发人员.""想要混的好,就得多努力." 写这些东西是因为毕竟看了书,但是看书看过去之后,也许印象不是很深刻,有些东西现在也理解不了,那我就把我理解的,现在就可以用到的东西,简单的写出来就好,让自己今后看到就能明白其中的意思. 还有就是锻炼一下表达,编辑能力,慢慢的提升自己,随时随地的都要有一个锻炼的心. 最后当然就