一、

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()); }
}

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

  1. JavaPersistenceWithMyBatis3笔记-第5章Configuring MyBatis in a Spring applications-001

    一. 1.Mapper /** * */ package com.mybatis3.mappers; import java.util.List; import org.apache.ibatis.a ...

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

    一. 1.Mapper /** * */ package com.mybatis3.mappers; import org.apache.ibatis.annotations.Select; impo ...

  3. JavaPersistenceWithMyBatis3笔记-第3章SQL Mappers Using XMLs-001

    一. 1.Mapper 2.Service 3.Domain package com.mybatis3.domain; import java.io.Serializable; import java ...

  4. JavaPersistenceWithMyBatis3笔记-第1章-001

    一.介绍 1.项目结构 2.数据库结构 二.代码 1.Mapper package com.mybatis3.mappers; import java.util.List; import com.my ...

  5. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)

    一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  7. Stealth视频教程学习笔记(第二章)

    Stealth视频教程学习笔记(第二章) 本文是对Unity官方视频教程Stealth的学习笔记.在此之前,本人整理了Stealth视频的英文字幕,并放到了优酷上.本文将分别对各个视频进行学习总结,提 ...

  8. Stealth视频教程学习笔记(第一章)

    Stealth视频教程学习笔记(第一章) 本文是对Unity官方视频教程Stealth的学习笔记.在此之前,本人整理了Stealth视频的英文字幕,并放到了优酷上.本文将分别对各个视频进行学习总结,提 ...

  9. 20145330《Java学习笔记》第一章课后练习8知识总结以及IDEA初次尝试

    20145330<Java学习笔记>第一章课后练习8知识总结以及IDEA初次尝试 题目: 如果C:\workspace\Hello\src中有Main.java如下: package cc ...

随机推荐

  1. 解决win10 phptoshop #fff纯白不是这样的白 显示器高级的问题

    1.打开控制面板,右上角搜索栏输入“颜色管理”, 再打开“颜色管理”.2.在“设备”选项卡里,“设备”下拉列表,选择“显示器”.3.可能你安装过显示器的驱动程序,下面的配置文件中会有一个默认的配置文件 ...

  2. 使用NSUserDefaults保存自定义对象(转)

    转自http://zani.iteye.com/blog/1431239 .h文件 #import <Foundation/Foundation.h> @interface MyObjec ...

  3. python3 xrange报错

    因为python3取消了xrange这个函数,range就是xrange.

  4. JQuery 提供了两种方式来阻止事件冒泡。

    JQuery 提供了两种方式来阻止事件冒泡. 方式一:event.stopPropagation(); $("#div1").mousedown(function(event){ ...

  5. LeetCode 293. Flip Game

    原题链接在这里:https://leetcode.com/problems/flip-game/description/ 题目: You are playing the following Flip ...

  6. NOIp2018集训test-10-24(am&pm)

    李巨连续AK三场了,我跟南瓜打赌李巨连续AK七场,南瓜赌李巨连续AK五场. DAY1 T1 qu 按题意拿stack,queue和priority_que模拟即可.特判没有元素却要取出的情况. T2 ...

  7. swing之JDialog

    package canying; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java ...

  8. java中初始化方法

    本文主要是讲从<java编程思想>中看到的东西,是第七章复用类的开头内容,主要是类初始化的几种方法的位置,主要包括 1.在定义对象的地方.这意味着他们总是在构造器被调用前被初始化. 2.在 ...

  9. Oracle记录(一)Oracle简介与安装

    Oracle笔记(一) Oracle简介及安装 一.轨迹 二.Oracle简介 Oracle是现在全世界最大的数据库提供商,编程语言提供商,应用软件提供商,它的地位等价于微软的地位. Oracle在古 ...

  10. 校赛热身 Problem C. Sometimes Naive (状压dp)

    题解: 列举每一种3的倍数的组合,开始先求出3条边的可行解,则 六条边的可行解可以由两个三条边得来. 详见代码解析 #include<bits/stdc++.h> using namesp ...