JavaPersistenceWithMyBatis3笔记-第2章Bootstrapping MyBatis-001XMl形式和Java形式
一、
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形式的更多相关文章
- JavaPersistenceWithMyBatis3笔记-第5章Configuring MyBatis in a Spring applications-001
一. 1.Mapper /** * */ package com.mybatis3.mappers; import java.util.List; import org.apache.ibatis.a ...
- JavaPersistenceWithMyBatis3笔记-第4章SQL Mappers Using Annotations-001
一. 1.Mapper /** * */ package com.mybatis3.mappers; import org.apache.ibatis.annotations.Select; impo ...
- JavaPersistenceWithMyBatis3笔记-第3章SQL Mappers Using XMLs-001
一. 1.Mapper 2.Service 3.Domain package com.mybatis3.domain; import java.io.Serializable; import java ...
- JavaPersistenceWithMyBatis3笔记-第1章-001
一.介绍 1.项目结构 2.数据库结构 二.代码 1.Mapper package com.mybatis3.mappers; import java.util.List; import com.my ...
- 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 ...
- 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 ...
- Stealth视频教程学习笔记(第二章)
Stealth视频教程学习笔记(第二章) 本文是对Unity官方视频教程Stealth的学习笔记.在此之前,本人整理了Stealth视频的英文字幕,并放到了优酷上.本文将分别对各个视频进行学习总结,提 ...
- Stealth视频教程学习笔记(第一章)
Stealth视频教程学习笔记(第一章) 本文是对Unity官方视频教程Stealth的学习笔记.在此之前,本人整理了Stealth视频的英文字幕,并放到了优酷上.本文将分别对各个视频进行学习总结,提 ...
- 20145330《Java学习笔记》第一章课后练习8知识总结以及IDEA初次尝试
20145330<Java学习笔记>第一章课后练习8知识总结以及IDEA初次尝试 题目: 如果C:\workspace\Hello\src中有Main.java如下: package cc ...
随机推荐
- jstat 简介(2)
jstat命令可以查看堆内存各部分的使用量,以及加载类的数量.命令的格式如下: jstat [-命令选项] [vmid] [间隔时间/毫秒] [查询次数] 注意:使用的jdk版本是jdk8. 类加载统 ...
- Hibernate(2)
一.实体类编写规则 1.实体类里面的属性属于私有的 2.私有属性使用公开的set和get方法操作 3.要求实体类有属性作为唯一值(一般使用id值) 4.实体类属性建议不要使用基本数据类型,使用基本数据 ...
- 一直想写的关于tarjan算法的理解——向struct edge大佬低头
tarjan的算法精髓就是dfn[]和low[]数组 dfn[i]表示在该节点被搜索的次序(时间戳) low[i]表示i或i的子树可以追溯到的最早的栈中节点 判断有强连通分量的条件就是 dfn[i]= ...
- 理解 JavaScript 对象原型、原型链如何工作、如何向 prototype 属性添加新的方法。
JavaScript 常被描述为一种基于原型的语言 (prototype-based language)——每个对象拥有一个原型对象,对象以其原型为模板.从原型继承方法和属性.原型对象也可能拥有原型, ...
- Android Volley完全解析(二),使用Volley加载网络图片
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17482165 在上一篇文章中,我们了解了Volley到底是什么,以及它的基本用法. ...
- Network Saboteur (深搜递归思想的特殊使用)
个人心得:对于深搜的使用还是不到位,对于递归的含义还是不太清楚!本来想着用深搜构成一个排列,然后从一到n分割成俩个数组,然后后面发现根本实现不了,思路太混乱.后来借鉴了网上的思想,发现用数组来标志,当 ...
- mysql开启和使用事件、与服务器重启mysql错误
一.mysql开启事件 首先用SHOW VARIABLES LIKE 'event_scheduler',查看计划事件有没有开启,他的返回值是off和on. 如果没有开启,可以在my.cnf配置文件中 ...
- centOS5.5 配置vnc,开启linux远程桌面
如何远程控制centOS桌面? 如何使用windows远程控制centOS桌面? 1.查看本机是否有安装vnc(centOS5默认有安装vnc) rpm -q vnc vnc-server 如果显示结 ...
- MongoDB数据库的备份和恢复
MongoDB数据库备份方式: 1.整库备份 2.单表备份 1.整库备份 备份整个数据库: mongodump -h 127.0.0.1:27000 -d park --authenticationD ...
- 一行删除所有docker container的命令
ns=`docker | awk '//{print $1}'`;for n in $ns;do docker rm -f $n;done docker | awk '{print $1}'|xarg ...