一、

1.Mapper

同上

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mybatis3.mappers.StudentMapper"> <resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
</resultMap> <select id="findAllStudents" resultMap="StudentResult">
select * from Students
</select> <select id="findStudentById" parameterType="int" resultType="Student">
select stud_id as studId, name, email, dob from Students where stud_id=#{studId}
</select> <insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
INSERT INTO STUDENTS(NAME,EMAIL,DOB) VALUES(#{name},#{email},#{dob})
</insert> <update id="updateStudent" parameterType="Student">
UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
</update> </mapper>

2.Service

同上

3.Domain

 /**
*
*/
package com.mybatis3.domain; /**
* @author Siva
*
*/
public class PhoneNumber
{
private String countryCode;
private String stateCode;
private String number; public PhoneNumber() {
} public PhoneNumber(String countryCode, String stateCode, String number) {
super();
this.countryCode = countryCode;
this.stateCode = stateCode;
this.number = number;
} public PhoneNumber(String string) {
if(string != null){
String[] parts = string.split("-");
if(parts.length>0) this.countryCode=parts[0];
if(parts.length>1) this.stateCode=parts[1];
if(parts.length>2) this.number=parts[2]; }
} @Override
public String toString() {
return this.getAsString();
} public String getCountryCode() {
return countryCode;
} public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
} public String getStateCode() {
return stateCode;
} public void setStateCode(String stateCode) {
this.stateCode = stateCode;
} public String getNumber() {
return number;
} public void setNumber(String number) {
this.number = number;
} public String getAsString() {
return countryCode+"-"+stateCode+"-"+number;
} }
 package com.mybatis3.domain;

 import java.util.Date;

 import org.apache.ibatis.type.Alias;

 /**
* @author Siva
*
*/
@Alias("Student")
public class Student
{
private Integer studId;
private String name;
private String email;
private Date dob; public Student() { } public Student(Integer studId) {
this.studId = studId;
} public Student(Integer studId, String name, String email, Date dob) {
this.studId = studId;
this.name = name;
this.email = email;
this.dob = dob;
} @Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email="
+ email + ", dob=" + dob + "]";
} public Integer getStudId() {
return studId;
}
public void setStudId(Integer studId) {
this.studId = studId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}

4.TypeHandler

 /**
*
*/
package com.mybatis3.typehandlers; import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType; import com.mybatis3.domain.PhoneNumber; /**
* @author Siva
*
*/
public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>{ @Override
public void setNonNullParameter(PreparedStatement ps, int i,
PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.getAsString());
} @Override
public PhoneNumber getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return new PhoneNumber(rs.getString(columnName));
} @Override
public PhoneNumber getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return new PhoneNumber(rs.getString(columnIndex));
} @Override
public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return new PhoneNumber(cs.getString(columnIndex));
} }

5.辅助类

 /**
*
*/
package com.mybatis3.util; import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource; import org.apache.ibatis.datasource.pooled.PooledDataSource; /**
* @author Siva
*
*/
public class DataSourceFactory
{
private static final Properties PROPERTIES = new Properties(); static
{
try {
InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
} public static DataSource getDataSource()
{
String driver = PROPERTIES.getProperty("jdbc.driverClassName");
String url = PROPERTIES.getProperty("jdbc.url");
String username = PROPERTIES.getProperty("jdbc.username");
String password = PROPERTIES.getProperty("jdbc.password");
PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);
return dataSource;
} public static DataSource getJNDIDataSource()
{
String dataSourceJNDIName = "java:comp/env/jdbc/MyBatisDemoDS";
try
{
InitialContext ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(dataSourceJNDIName);
return dataSource;
}
catch (NamingException e)
{
throw new RuntimeException(e);
}
}
}
 package com.mybatis3.util;

 import java.io.IOException;
import java.io.InputStream; import javax.sql.DataSource; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.typehandlers.PhoneTypeHandler; /**
* @author Siva
*
*/
public class MyBatisUtil
{
private static SqlSessionFactory xmlSqlSessionFactory;
private static SqlSessionFactory javaSqlSessionFactory; public static SqlSessionFactory getSqlSessionFactoryUsingXML()
{
if(xmlSqlSessionFactory==null)
{
InputStream inputStream;
try
{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
xmlSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e)
{
throw new RuntimeException(e);
}
}
return xmlSqlSessionFactory;
} public static SqlSessionFactory getSqlSessionFactoryUsingJavaAPI()
{
if(javaSqlSessionFactory==null)
{
try
{
DataSource dataSource = DataSourceFactory.getDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.getTypeAliasRegistry().registerAlias("student", Student.class);
configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.class);
configuration.addMapper(StudentMapper.class);
javaSqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); }catch (Exception e)
{
throw new RuntimeException(e);
}
}
return javaSqlSessionFactory;
} }

6.配置及资源文件

(1)mybatis-config.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <properties resource="application.properties">
<property name="jdbc.username" value="root"/>
<property name="jdbc.password" value="verysecurepwd"/>
</properties> <!-- <settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings> --> <typeAliases>
<package name="com.mybatis3.domain"/>
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
<!-- <package name="com.mybatis3.mappers"/> -->
</mappers> </configuration>

(2)full-mybatis-config.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <!-- This file is for a reference purpose for various configuration options -->
<properties resource="application.properties">
<property name="username" value="db_user"/>
<property name="password" value="verysecurepwd"/>
</properties> <settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings> <typeAliases>
<typeAlias alias="Tutor" type="com.mybatis3.domain.Tutor"/>
<package name="com.mybatis3.domain"/>
</typeAliases> <typeHandlers>
<typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/>
<package name="com.mybatis3.typehandlers"/>
</typeHandlers> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment> <environment id="production">
<transactionManager type="JDBC"/>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/jdbc/MyBatisDemoDS"/>
</dataSource>
</environment> </environments> <mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
<mapper url="file:///var/mappers/StudentMapper.xml"/>
<mapper class="com.mybatis3.mappers.TutorMapper"/>
</mappers> </configuration>

7.测试文件

 package com.mybatis3.services;

 import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import java.util.Date;
import java.util.List; import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test; import com.mybatis3.domain.Student;
import com.mybatis3.util.MyBatisUtil; public class StudentServiceTest
{
private static StudentService studentService; @BeforeClass
public static void setup()
{
TestDataPopulator.initDatabase(); SqlSessionFactory sqlSessionFactory = null;
//Use this if you want XML based configuration
sqlSessionFactory = MyBatisUtil.getSqlSessionFactoryUsingXML(); //Use this if you want to use Java API configuration
//sqlSessionFactory = MyBatisUtil.getSqlSessionFactoryUsingJavaAPI();
studentService = new StudentService(sqlSessionFactory);
} @AfterClass
public static void teardown()
{
studentService = null;
} @Test
public void testFindAllStudents()
{
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
assertNotNull(student);
System.out.println(student);
} } @Test
public void testFindStudentById()
{
Student student = studentService.findStudentById(1);
assertNotNull(student);
} @Test
public void testCreateUStudent()
{
Student student = new Student();
int id = 4;
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
student.setDob(new Date());
Student newStudent = studentService.createStudent(student);
assertNotNull(newStudent);
assertEquals("student_"+id, newStudent.getName());
assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
} @Test
public void testUpdateStudent()
{
int id = 2;
Student student =studentService.findStudentById(id);
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
Date now = new Date();
student.setDob(now);
studentService.updateStudent(student);
Student updatedStudent = studentService.findStudentById(id);
assertNotNull(updatedStudent);
assertEquals("student_"+id, updatedStudent.getName());
assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail()); }
}

最新文章

  1. SCNU 2015ACM新生赛决赛【F. Oyk闯机关】解题报告
  2. final关键字(final是最终的)
  3. Java 链表
  4. ural 1338. Automobiles
  5. 关于URL、Web的一些概念
  6. jquery只能输入数字方法
  7. js文本框提示和自动完成
  8. MVC中html转义问题(直接输出html的方法)
  9. ORACLE 查询日志
  10. 编绎openssl杂记(window)
  11. 给jdk写注释系列之jdk1.6容器(11)-Queue之ArrayDeque源码解析
  12. javascript Date类型 学习笔记
  13. HashMap HashTable HashSet区别剖析
  14. 配置QtCreator+CDB远程调试环境(要设置_NT_SYMBOL_PATH和QT_PLUGIN_PATH和Path)
  15. windows命令中的cd
  16. 跟面试官聊.NET垃圾收集,直刺面试官G点
  17. 【UOJ#236】[IOI2016]railroad(欧拉回路,最小生成树)
  18. GBDT 详解分析 转+整理
  19. ant___令牌过滤器
  20. ruby导出exl方式

热门文章

  1. C#中的线程(二)线程同步
  2. k-means算法的优缺点以及改进
  3. 要做Java程序员 需要知道那些技术 重点有那些
  4. C程序设计语言阅读笔记
  5. 使用range()生成自然数序列
  6. linux下使用fstat来计算文件的大小
  7. 学习动态性能表(8)--v$lock&amp;v$locked_object
  8. 在C#中实现截获shell程序的输出
  9. Windows命令行操作MySQL
  10. 使用script转储终端命令输出,或者录制并播放session的内容