JavaPersistenceWithMyBatis3笔记-第5章Configuring MyBatis in a Spring applications-001
一、
1.Mapper
/**
*
*/
package com.mybatis3.mappers; import java.util.List; import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider; import com.mybatis3.domain.Course;
import com.mybatis3.domain.Tutor;
import com.mybatis3.sqlproviders.TutorDynaSqlProvider; /**
* @author Siva
*
*/ public interface TutorMapper
{ @Select("select * from courses where tutor_id=#{tutorId}")
@ResultMap("com.mybatis3.mappers.TutorMapper.CourseResult")
List<Course> selectCoursesByTutorId(int tutorId); @Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tutors t where t.tutor_id=#{tutorId}")
@Results({
@Result(id=true, column="tutor_id", property="tutorId"),
@Result(column="tutor_name", property="name"),
@Result(column="email", property="email"),
@Result(property="address", column="addr_id",
one=@One(select="com.mybatis3.mappers.AddressMapper.selectAddressById")),
@Result(property="courses", column="tutor_id",
many=@Many(select="com.mybatis3.mappers.TutorMapper.selectCoursesByTutorId"))
})
Tutor selectTutorWithCoursesById(int tutorId); @SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutorsSql")
List<Tutor> findAllTutors(); @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql")
Tutor findTutorById(int tutorId); @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNameAndEmailSql")
Tutor findTutorByNameAndEmail(@Param("name")String name, @Param("email")String email); @InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor")
@Options(useGeneratedKeys=true, keyProperty="tutorId")
int insertTutor(Tutor tutor); @UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor")
int updateTutor(Tutor tutor); @DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor")
int deleteTutor(int tutorId); @SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorById")
@ResultMap("com.mybatis3.mappers.TutorMapper.TutorResult")
Tutor selectTutorById(int tutorId); }
2.Service
package com.mybatis3.services; import java.util.List;
import java.util.Map; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.mybatis3.domain.Address;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.AddressMapper;
import com.mybatis3.mappers.StudentMapper; @Service
@Transactional
public class StudentService
{
private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private StudentMapper studentMapper; @Autowired
private AddressMapper addressMapper; public List<Student> findAllStudents() {
return studentMapper.findAllStudents();
} public Student findStudentById(Integer id) {
logger.debug("findStudentById :"+id);
return studentMapper.findStudentById(id);
} public Student findStudentWithAddressById(int id) {
return studentMapper.selectStudentWithAddress(id);
} public Student createStudent(Student student) {
Address address = student.getAddress();
if(address != null){
addressMapper.insertAddress(address);
}
if(student.getName()==null || student.getName().trim().length()==0){
throw new RuntimeException("Student Name should not be null");
}
studentMapper.insertStudent(student);
return student;
} public void createStudentWithMap(Map<String, Object> studentDataMap) {
studentMapper.insertStudentWithMap(studentDataMap);
} public Student updateStudent(Student student) {
studentMapper.updateStudent(student);
return student;
} public boolean deleteStudent(int id) {
int count = studentMapper.deleteStudent(id);
return count > 0;
} public Map<String, Object> findStudentMapById(int id) {
return studentMapper.findStudentMapById(id);
} public List<Map<String, Object>> findAllStudentsMap() {
return studentMapper.findAllStudentsMap();
}
}
/**
*
*/
package com.mybatis3.services; import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.mybatis3.domain.Tutor;
import com.mybatis3.mappers.TutorMapper; /**
* @author Siva
*
*/
@Service
@Transactional
public class TutorService
{
@Autowired
private SqlSession sqlSession; private TutorMapper getTutorMapper(){
return sqlSession.getMapper(TutorMapper.class);
}
public List<Tutor> findAllTutors() {
return getTutorMapper().findAllTutors();
} public Tutor findTutorById(int tutorId) {
return getTutorMapper().findTutorById(tutorId);
} public Tutor findTutorByNameAndEmail(String name, String email) {
return getTutorMapper().findTutorByNameAndEmail(name, email);
} public Tutor createTutor(Tutor tutor) {
getTutorMapper().insertTutor(tutor);
return tutor;
} public Tutor updateTutor(Tutor tutor) {
getTutorMapper().updateTutor(tutor);
return tutor;
} public boolean deleteTutor(int tutorId) {
boolean deleted = false;
int nor = getTutorMapper().deleteTutor(tutorId);
deleted = (nor == 1);
return deleted;
} public Tutor selectTutorById(int tutorId) {
return getTutorMapper().selectTutorById(tutorId);
} public Tutor selectTutorWithCoursesById(int tutorId) {
return getTutorMapper().selectTutorWithCoursesById(tutorId);
}
}
3.Domain
4.辅助类
/**
*
*/
package com.mybatis3.sqlproviders; import java.util.Map; import org.apache.ibatis.jdbc.SQL; import com.mybatis3.domain.Tutor;
/**
* @author Siva
*
*/
public class TutorDynaSqlProvider
{ public String findAllTutorsSql()
{
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
}}.toString();
} public String findTutorByIdSql(final int tutorId)
{
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("tutor_id="+tutorId);
}}.toString();
} public String findTutorByNameAndEmailSql(Map<String, Object> map)
{
//String name = (String) map.get("name");
//String email = (String) map.get("email");
//System.err.println(name+":"+email);
return new SQL() {{
SELECT("tutor_id as tutorId, name, email");
FROM("tutors");
WHERE("name=#{name} AND email=#{email}");
}}.toString();
} public String insertTutor(final Tutor tutor) {
return new SQL() {{
INSERT_INTO("TUTORS"); if (tutor.getName() != null) {
VALUES("NAME", "#{name}");
} if (tutor.getEmail() != null) {
VALUES("EMAIL", "#{email}");
}
}}.toString();
} public String updateTutor(final Tutor tutor)
{
return new SQL() {{
UPDATE("TUTORS"); if (tutor.getName() != null) {
SET("NAME = #{name}");
} if (tutor.getEmail() != null) {
SET("EMAIL = #{email}");
}
WHERE("TUTOR_ID = #{tutorId}");
}}.toString();
} public String deleteTutor(int tutorId)
{
return new SQL() {{
DELETE_FROM("TUTORS");
WHERE("TUTOR_ID = #{tutorId}");
}}.toString();
} public String selectTutorById()
{
return new SQL() {{
SELECT("t.tutor_id, t.name as tutor_name, email, a.addr_id, street, city, state, zip, country,course_id, c.name as course_name, description, start_date, end_date");
FROM("TUTORS t");
LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id");
LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id");
WHERE("t.TUTOR_ID = #{tutorId}");
}}.toString();
}
}
5.配置及资源文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"> <context:annotation-config /> <context:component-scan base-package="com.mybatis3" /> <context:property-placeholder location="classpath:application.properties" /> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- <mybatis:scan base-package="com.mybatis3.mappers"/> --> <!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mybatis3.mappers" />
</bean> --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.mybatis3.domain"/>
<property name="typeHandlersPackage" value="com.mybatis3.typehandlers"/>
<property name="mapperLocations" value="classpath*:com/mybatis3/**/*.xml" />
</bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> </beans>
mapper.xml同上
package com.mybatis3.config; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/*
import javax.sql.DataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
*/
/**
* @author Siva
*
*/
@Configuration
@MapperScan(value="com.mybatis3.mappers")
public class AppConfig
{
/*
@Bean
public DataSource dataSource() {
return new PooledDataSource("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/elearning",
"root", "admin");
} @Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
*/
}
6.测试文件
package com.mybatis3.services; import static org.junit.Assert.*; import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mybatis3.domain.Address;
import com.mybatis3.domain.PhoneNumber;
import com.mybatis3.domain.Student; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class StudentServiceTest
{
@Autowired
private StudentService studentService; @BeforeClass
public static void setup() {
TestDataPopulator.initDatabase();
} @Test
public void testFindAllStudents() {
List<Student> students = studentService.findAllStudents();
assertNotNull(students);
for (Student student : students)
{
System.err.println(student);
}
} @Test
public void testFindStudentById() {
Student student = studentService.findStudentById(1);
System.err.println(student);
System.err.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity()); } @Test
public void testFindStudentWithAddressById() {
Student student = studentService.findStudentWithAddressById(2);
assertNotNull(student);
System.out.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
} @Test
public void testCreateStudent() {
//Address address = new Address();
Address address = new Address(1,"Quaker Ridge Rd.","Bethel","Brooklyn","06801","USA");
/*address.setStreet("Quaker Ridge Rd.");
address.setCity("Bethel");
address.setState("Brooklyn");
address.setZip("06801");
address.setCountry("USA");*/ Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("stud_"+ts+"@gmail.com");
stud.setPhone(new PhoneNumber("123-456-7890"));
stud.setAddress(address);
Student student = studentService.createStudent(stud);
assertNotNull(student);
assertEquals("stud_"+ts, student.getName());
assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
System.err.println("CreatedStudent: "+student);
} @Test(expected=DataAccessException.class)
public void testCreateStudentForException() {
Address address = new Address();
address.setStreet("Quaker Ridge Rd.");
address.setCity("Bethel");
address.setState("Brooklyn");
address.setZip("06801");
address.setCountry("USA"); Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("timothy@gmail.com");
stud.setPhone(new PhoneNumber("123-456-7890"));
stud.setAddress(address);
studentService.createStudent(stud);
fail("You should not reach here");
} @Test
public void testCreateStudentWithMap() {
Map<String, Object> studMap = new HashMap<String, Object>();
long ts = System.currentTimeMillis();
studMap.put("name","stud_"+ts);
studMap.put("email","stud_"+ts+"@gmail.com");
studMap.put("phone",null);
studentService.createStudentWithMap(studMap);
} @Test
public void testUpdateStudent() {
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setStudId(2);
stud.setName("studddd_"+ts);
stud.setEmail("studddd_"+ts+"@gmail.com");
Student student = studentService.updateStudent(stud);
assertNotNull(student);
assertEquals("studddd_"+ts, student.getName());
assertEquals("studddd_"+ts+"@gmail.com", student.getEmail());
assertEquals(new Integer(2), student.getStudId()); System.out.println("UpdatedStudent: "+student);
} @Test
public void testDeleteStudent() {
boolean deleted = studentService.deleteStudent(3);
assertTrue(deleted);
System.err.println("deleteStudent:"+deleted);
} @Test
public void testFindStudentMapById() {
Map<String, Object> studentMap = studentService.findStudentMapById(1);
System.err.println(studentMap);
} @Test
public void testFindAllStudentsMap() {
List<Map<String,Object>> studentMapList = studentService.findAllStudentsMap();
for(Map<String,Object> studentMap : studentMapList)
{
System.out.println("id :"+studentMap.get("id"));
System.out.println("name :"+studentMap.get("name"));
System.out.println("email :"+studentMap.get("email"));
System.out.println("phone :"+studentMap.get("phone"));
}
} }
package com.mybatis3.services; import static org.junit.Assert.*; import java.util.List; import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mybatis3.domain.Tutor; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TutorServiceTest
{
@Autowired
private TutorService tutorService; @BeforeClass
public static void setup() {
TestDataPopulator.initDatabase();
} @Test
public void testFindAllTutors() {
List<Tutor> tutors = tutorService.findAllTutors();
assertNotNull(tutors);
for (Tutor tutor : tutors)
{
System.err.println(tutor);
}
} @Test
public void testFindTutorById() {
Tutor tutor = tutorService.findTutorById(1);
assertNotNull(tutor);
//System.err.println(tutor);
} @Test
public void testFindTutorByNameAndEmail() {
Tutor tutor = tutorService.findTutorByNameAndEmail("Paul", "paul@gmail.com");
assertNotNull(tutor);
//System.err.println(tutor);
} @Test
public void testCreateTutor() {
Tutor tutor = new Tutor();
tutor.setName("siva");
tutor.setEmail("siva@gmail.com");
tutor = tutorService.createTutor(tutor);
assertNotNull(tutor);
} @Test
public void testUpdateTutor() {
Tutor tutor = new Tutor();
tutor.setTutorId(1);
tutor.setName("sivaprasad");
tutor.setEmail("sivaprasad@gmail.com");
tutor = tutorService.updateTutor(tutor);
Tutor updTutor = tutorService.findTutorById(1);
assertNotNull(updTutor);
System.err.println(updTutor);
} @Test
public void testDeleteTutor() {
boolean deleted = tutorService.deleteTutor(4);
assertTrue(deleted);
} @Test
public void testSelectTutorById() {
Tutor tutor = tutorService.selectTutorById(1);
assertNotNull(tutor);
System.err.println(tutor);
} @Test
public void testSelectTutorWithCoursesById() {
Tutor tutor = tutorService.selectTutorWithCoursesById(1);
assertNotNull(tutor);
System.err.println(tutor);
} }
JavaPersistenceWithMyBatis3笔记-第5章Configuring MyBatis in a Spring applications-001的更多相关文章
- 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笔记-第2章Bootstrapping MyBatis-001XMl形式和Java形式
一. 1.Mapper 同上 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper ...
- JavaPersistenceWithMyBatis3笔记-第1章-001
一.介绍 1.项目结构 2.数据库结构 二.代码 1.Mapper package com.mybatis3.mappers; import java.util.List; import com.my ...
- 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 ...
- java JDK8 学习笔记——第16章 整合数据库
第十六章 整合数据库 16.1 JDBC入门 16.1.1 JDBC简介 1.JDBC是java联机数据库的标准规范.它定义了一组标准类与接口,标准API中的接口会有数据库厂商操作,称为JDBC驱动程 ...
- CSS3秘笈第三版涵盖HTML5学习笔记1~5章
第一部分----CSS基础知识 第1章,CSS需要的HTML HTML越简单,对搜索引擎越友好 div是块级元素,span是行内元素 <section>标签包含一组相关的内容,就像一本书中 ...
随机推荐
- 解决get方法传递URL参数中文乱码问题
[转]解决get方法传递URL参数中文乱码问题 来自:http://www.javaeye.com/topic/483158 应用一:解决tomcat下中文乱码问题(先来个简单的) 在tomcat下, ...
- 百度浏览器极速模式下访问 FastAdmin 的问题
百度浏览器极速模式下访问 FastAdmin 的问题 兼容性问题,因为 https 证书配置时对低版本的浏览器不适配引起. 应该是 百度浏览器的内核太旧,没有更新导致.
- (转)Android 50道面试题总结(大家看看吧)
1. 方法重载与覆盖的区别?(Overload与Override的区别)2. String 和StringBuffer的区别3. 字符串“abcde”通过写一个函数不让调用第三方的字符串,实现一个字符 ...
- jenkin执行权限问题
jenkins执行报错 stderr: Permission denied, please try again. Permission denied, please try again. Permis ...
- HTTP/HTTPS原理详解
简介 HTTP(Hypertext Transfer Protocal,超文本传输协议)是WWW(World Wide Web,万维网)数据传输的基础,规定如何传输超文本.HTTP协议存在多个版本:H ...
- gen_server模块
转自http://www.xuebuyuan.com/2132233.html
- 使用妹子UI开发的体验分享
前阵子看到一个类似bootstrap的前端UI框架,好奇心驱使下,去琢磨了一些,最终决定网站改版用这个UI试试效果: 首页+头部: 投稿页: 现成拷贝过来的评论列表: 总结: 上手难度: (熟悉boo ...
- 浅谈FPGA有限状态机
状态机几乎可以实现一切时序电路. 有限状态机(FiniteStateMachine, FSM),根据状态机的输出是否与输入有关,可分为Moore型状态机和Mealy型状态机.Moore型状态机输出仅仅 ...
- Apache CXF使用Jetty发布WebService
一.概述 Apache CXF提供了用于方便地构建和开发WebService的可靠基础架构.它允许创建高性能和可扩展的服务,可以部署在Tomcat和基于Spring的轻量级容器中,也可以部署在更高级的 ...
- Spring Batch介绍
简介 SpringBatch 是一个大数据量的并行处理框架.通常用于数据的离线迁移,和数据处理,⽀持事务.并发.流程.监控.纵向和横向扩展,提供统⼀的接⼝管理和任务管理;SpringBatch是Spr ...