您的位置:首页 > 移动开发

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

2016-04-27 19:32 681 查看
一、

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

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: