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

一、

1.Mapper

 1 /**
 2  * 
 3  */
 4 package com.mybatis3.mappers;
 5 
 6 import java.util.List;
 7 
 8 import org.apache.ibatis.annotations.DeleteProvider;
 9 import org.apache.ibatis.annotations.InsertProvider;
10 import org.apache.ibatis.annotations.Many;
11 import org.apache.ibatis.annotations.One;
12 import org.apache.ibatis.annotations.Options;
13 import org.apache.ibatis.annotations.Param;
14 import org.apache.ibatis.annotations.Result;
15 import org.apache.ibatis.annotations.ResultMap;
16 import org.apache.ibatis.annotations.Results;
17 import org.apache.ibatis.annotations.Select;
18 import org.apache.ibatis.annotations.SelectProvider;
19 import org.apache.ibatis.annotations.UpdateProvider;
20 
21 import com.mybatis3.domain.Course;
22 import com.mybatis3.domain.Tutor;
23 import com.mybatis3.sqlproviders.TutorDynaSqlProvider;
24 
25 
26 /**
27  * @author Siva
28  *
29  */
30 
31 public interface TutorMapper 
32 {
33     
34     @Select("select * from courses where tutor_id=#{tutorId}")
35     @ResultMap("com.mybatis3.mappers.TutorMapper.CourseResult")
36     List selectCoursesByTutorId(int tutorId);
37     
38     @Select("SELECT tutor_id, t.name as tutor_name, email, addr_id FROM tutors t where t.tutor_id=#{tutorId}")
39     @Results({
40         @Result(id=true, column="tutor_id", property="tutorId"),
41         @Result(column="tutor_name", property="name"),
42         @Result(column="email", property="email"),
43         @Result(property="address", column="addr_id",
44                 one=@One(select="com.mybatis3.mappers.AddressMapper.selectAddressById")),        
45         @Result(property="courses", column="tutor_id",
46                 many=@Many(select="com.mybatis3.mappers.TutorMapper.selectCoursesByTutorId"))        
47     })
48     Tutor selectTutorWithCoursesById(int tutorId);
49     
50     @SelectProvider(type=TutorDynaSqlProvider.class, method="findAllTutorsSql")
51     List findAllTutors();
52     
53     @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql")
54     Tutor findTutorById(int tutorId);
55     
56     @SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByNameAndEmailSql")
57     Tutor findTutorByNameAndEmail(@Param("name")String name, @Param("email")String email);
58     
59     @InsertProvider(type=TutorDynaSqlProvider.class, method="insertTutor")
60     @Options(useGeneratedKeys=true, keyProperty="tutorId")
61     int insertTutor(Tutor tutor);
62     
63     @UpdateProvider(type=TutorDynaSqlProvider.class, method="updateTutor")
64     int updateTutor(Tutor tutor);
65     
66     @DeleteProvider(type=TutorDynaSqlProvider.class, method="deleteTutor")
67     int deleteTutor(int tutorId);
68         
69     @SelectProvider(type=TutorDynaSqlProvider.class, method="selectTutorById")
70     @ResultMap("com.mybatis3.mappers.TutorMapper.TutorResult")
71     Tutor selectTutorById(int tutorId);
72     
73     
74 }

 

2.Service

 1 package com.mybatis3.services;
 2 
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import org.slf4j.Logger;
 7 import org.slf4j.LoggerFactory;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Service;
10 import org.springframework.transaction.annotation.Transactional;
11 
12 import com.mybatis3.domain.Address;
13 import com.mybatis3.domain.Student;
14 import com.mybatis3.mappers.AddressMapper;
15 import com.mybatis3.mappers.StudentMapper;
16 
17 
18 @Service
19 @Transactional
20 public class StudentService 
21 {
22     private Logger logger = LoggerFactory.getLogger(getClass());
23     
24     @Autowired
25     private StudentMapper studentMapper;
26     
27     @Autowired
28     private AddressMapper addressMapper;
29     
30     public List findAllStudents() {
31         return studentMapper.findAllStudents();        
32     }
33     
34     public Student findStudentById(Integer id) {
35         logger.debug("findStudentById :"+id);
36         return studentMapper.findStudentById(id);        
37     }
38 
39     public Student findStudentWithAddressById(int id) {
40         return studentMapper.selectStudentWithAddress(id);        
41     }
42     
43     public Student createStudent(Student student) {
44         Address address = student.getAddress();
45         if(address != null){
46             addressMapper.insertAddress(address);
47         }
48         if(student.getName()==null || student.getName().trim().length()==0){
49             throw new RuntimeException("Student Name should not be null");
50         }
51         studentMapper.insertStudent(student);
52         return student;
53     }
54     
55     public void createStudentWithMap(Map studentDataMap) {
56         studentMapper.insertStudentWithMap(studentDataMap);
57     }
58 
59     public Student updateStudent(Student student) {
60         studentMapper.updateStudent(student);
61         return student;
62     }
63     
64     public boolean deleteStudent(int id) {
65         int count = studentMapper.deleteStudent(id);
66         return count > 0;
67     }
68     
69     public Map findStudentMapById(int id) {
70         return studentMapper.findStudentMapById(id);
71     }
72 
73     public List> findAllStudentsMap() {
74         return studentMapper.findAllStudentsMap();
75     }
76 }

 

 1 /**
 2  * 
 3  */
 4 package com.mybatis3.services;
 5 
 6 import java.util.List;
 7 
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Service;
11 import org.springframework.transaction.annotation.Transactional;
12 
13 import com.mybatis3.domain.Tutor;
14 import com.mybatis3.mappers.TutorMapper;
15 
16 
17 /**
18  * @author Siva
19  *
20  */
21 @Service
22 @Transactional
23 public class TutorService 
24 {
25     @Autowired
26     private SqlSession sqlSession;
27     
28     private TutorMapper getTutorMapper(){
29         return sqlSession.getMapper(TutorMapper.class);
30     }
31     public List findAllTutors() {
32         return getTutorMapper().findAllTutors();
33     }
34     
35     public Tutor findTutorById(int tutorId) {
36         return getTutorMapper().findTutorById(tutorId);
37     }
38     
39     public Tutor findTutorByNameAndEmail(String name, String email) {
40         return getTutorMapper().findTutorByNameAndEmail(name, email);
41     }
42     
43     public Tutor createTutor(Tutor tutor) {
44         getTutorMapper().insertTutor(tutor);
45         return tutor;
46     }
47     
48     public Tutor updateTutor(Tutor tutor) {
49         getTutorMapper().updateTutor(tutor);
50         return tutor;
51     }
52     
53     public boolean deleteTutor(int tutorId) {
54         boolean deleted = false;
55         int nor = getTutorMapper().deleteTutor(tutorId);
56         deleted = (nor == 1);
57         return deleted;
58     }
59     
60     public Tutor selectTutorById(int tutorId) {
61         return getTutorMapper().selectTutorById(tutorId);
62     }
63     
64     public Tutor selectTutorWithCoursesById(int tutorId) {
65         return getTutorMapper().selectTutorWithCoursesById(tutorId);
66     }
67 }

 

3.Domain

4.辅助类

 1 /**
 2  * 
 3  */
 4 package com.mybatis3.sqlproviders;
 5 
 6 import java.util.Map;
 7 
 8 import org.apache.ibatis.jdbc.SQL;
 9 
10 import com.mybatis3.domain.Tutor;
11 /**
12  * @author Siva
13  *
14  */
15 public class TutorDynaSqlProvider 
16 {
17 
18     public String findAllTutorsSql() 
19     {
20         return new SQL() {{
21         SELECT("tutor_id as tutorId, name, email");
22         FROM("tutors");
23         }}.toString();
24     }
25     
26     public String findTutorByIdSql(final int tutorId) 
27     {
28         return new SQL() {{
29         SELECT("tutor_id as tutorId, name, email");
30         FROM("tutors");
31         WHERE("tutor_id="+tutorId);
32         }}.toString();
33     }
34     
35     
36     public String findTutorByNameAndEmailSql(Map map) 
37     {
38         //String name = (String) map.get("name");
39         //String email = (String) map.get("email");
40         //System.err.println(name+":"+email);
41         return new SQL() {{
42         SELECT("tutor_id as tutorId, name, email");
43         FROM("tutors");
44         WHERE("name=#{name} AND email=#{email}");
45         }}.toString();
46     }
47     
48     public String insertTutor(final Tutor tutor) {
49         return new SQL() {{
50         INSERT_INTO("TUTORS");
51         
52         if (tutor.getName() != null) {
53             VALUES("NAME", "#{name}");
54         }
55         
56         if (tutor.getEmail() != null) {
57             VALUES("EMAIL", "#{email}");
58         }
59         }}.toString();
60     }
61     
62     public String updateTutor(final Tutor tutor) 
63     {
64         return new SQL() {{
65         UPDATE("TUTORS");
66         
67         if (tutor.getName() != null) {
68             SET("NAME = #{name}");
69         }
70         
71         if (tutor.getEmail() != null) {
72             SET("EMAIL = #{email}");
73         }
74         WHERE("TUTOR_ID = #{tutorId}");
75         }}.toString();
76     }
77     
78     public String deleteTutor(int tutorId) 
79     {
80         return new SQL() {{
81         DELETE_FROM("TUTORS");
82         WHERE("TUTOR_ID = #{tutorId}");
83         }}.toString();
84     }
85     
86     public String selectTutorById() 
87     {        
88         return new SQL() {{
89         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");
90         FROM("TUTORS t");
91         LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id");
92         LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id");
93         WHERE("t.TUTOR_ID = #{tutorId}");
94         }}.toString();        
95     }
96 }

 

5.配置及资源文件

applicationContext.xml

 1 
 2  3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:p="http://www.springframework.org/schema/p"
 7     xmlns:tx="http://www.springframework.org/schema/tx"
 8     xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
 9     xsi:schemaLocation="http://www.springframework.org/schema/beans 
10                         http://www.springframework.org/schema/beans/spring-beans.xsd
11                         http://www.springframework.org/schema/aop 
12                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
13                         http://www.springframework.org/schema/context 
14                         http://www.springframework.org/schema/context/spring-context.xsd
15                         http://www.springframework.org/schema/tx 
16                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
17                         http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
18     
19     
20 
21     package="com.mybatis3" />
22 
23     
24     
25      
26     
27     
28     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
29           
30     
31     
32     
33     
34     
37 
38     class="org.mybatis.spring.SqlSessionTemplate">
39       
40     
41     
42        class="org.mybatis.spring.SqlSessionFactoryBean">
43           
44           
45           
46           
47     
48     
49      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
50         
51         
52         
53         
54     
55     
56 

 

mapper.xml同上

 

 1 package com.mybatis3.config;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.context.annotation.Configuration;
 5 /*
 6 import javax.sql.DataSource;
 7 import org.apache.ibatis.datasource.pooled.PooledDataSource;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.mybatis.spring.SqlSessionFactoryBean;
10 import org.springframework.context.annotation.Bean;
11 */
12 /**
13  * @author Siva
14  *
15  */
16 @Configuration
17 @MapperScan(value="com.mybatis3.mappers")
18 public class AppConfig
19 {
20     /*
21     @Bean
22     public DataSource dataSource() {
23         return new PooledDataSource("com.mysql.jdbc.Driver", 
24                                     "jdbc:mysql://localhost:3306/elearning", 
25                                     "root", "admin");
26     }
27     
28     @Bean
29     public SqlSessionFactory sqlSessionFactory() throws Exception {
30         SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
31         sessionFactory.setDataSource(dataSource());
32         return sessionFactory.getObject();
33     }
34     */
35 }

 

6.测试文件

  1 package com.mybatis3.services;
  2 
  3 import static org.junit.Assert.*;
  4 
  5 import java.util.HashMap;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import org.junit.BeforeClass;
 10 import org.junit.Test;
 11 import org.junit.runner.RunWith;
 12 import org.springframework.beans.factory.annotation.Autowired;
 13 import org.springframework.dao.DataAccessException;
 14 import org.springframework.test.context.ContextConfiguration;
 15 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 16 
 17 import com.mybatis3.domain.Address;
 18 import com.mybatis3.domain.PhoneNumber;
 19 import com.mybatis3.domain.Student;
 20 
 21 @RunWith(SpringJUnit4ClassRunner.class)
 22 @ContextConfiguration(locations="classpath:applicationContext.xml")
 23 public class StudentServiceTest 
 24 {
 25     @Autowired
 26     private StudentService studentService;
 27     
 28     @BeforeClass
 29     public static void setup() {
 30         TestDataPopulator.initDatabase();
 31     }
 32     
 33     @Test
 34     public void testFindAllStudents() {
 35         List students = studentService.findAllStudents();
 36         assertNotNull(students);
 37         for (Student student : students)
 38         {
 39             System.err.println(student);
 40         }
 41     }
 42 
 43     @Test
 44     public void testFindStudentById() {
 45         Student student = studentService.findStudentById(1);
 46         System.err.println(student);
 47         System.err.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
 48         
 49     }
 50 
 51     @Test
 52     public void testFindStudentWithAddressById() {
 53         Student student = studentService.findStudentWithAddressById(2);
 54         assertNotNull(student);
 55         System.out.println(student.getAddress().getAddrId()+":"+student.getAddress().getCity());
 56     }
 57 
 58     @Test
 59     public void testCreateStudent() {
 60         //Address address = new Address();
 61         Address address = new Address(1,"Quaker Ridge Rd.","Bethel","Brooklyn","06801","USA");
 62         /*address.setStreet("Quaker Ridge Rd.");
 63         address.setCity("Bethel");
 64         address.setState("Brooklyn");
 65         address.setZip("06801");
 66         address.setCountry("USA");*/
 67         
 68         Student stud = new Student();
 69         long ts = System.currentTimeMillis();
 70         stud.setName("stud_"+ts);
 71         stud.setEmail("stud_"+ts+"@gmail.com");
 72         stud.setPhone(new PhoneNumber("123-456-7890"));
 73         stud.setAddress(address);
 74         Student student = studentService.createStudent(stud);
 75         assertNotNull(student);
 76         assertEquals("stud_"+ts, student.getName());
 77         assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
 78         System.err.println("CreatedStudent: "+student);
 79     }
 80 
 81     @Test(expected=DataAccessException.class)
 82     public void testCreateStudentForException() {
 83         Address address = new Address();
 84         address.setStreet("Quaker Ridge Rd.");
 85         address.setCity("Bethel");
 86         address.setState("Brooklyn");
 87         address.setZip("06801");
 88         address.setCountry("USA");
 89         
 90         Student stud = new Student();
 91         long ts = System.currentTimeMillis();
 92         stud.setName("stud_"+ts);
 93         stud.setEmail("[email protected]");
 94         stud.setPhone(new PhoneNumber("123-456-7890"));
 95         stud.setAddress(address);
 96         studentService.createStudent(stud);
 97         fail("You should not reach here");
 98     }
 99     
100     @Test
101     public void testCreateStudentWithMap() {
102         Map studMap = new HashMap();
103         long ts = System.currentTimeMillis();
104         studMap.put("name","stud_"+ts);
105         studMap.put("email","stud_"+ts+"@gmail.com");
106         studMap.put("phone",null);
107         studentService.createStudentWithMap(studMap);
108     }
109 
110     @Test
111     public void testUpdateStudent() {
112         Student stud = new Student();
113         long ts = System.currentTimeMillis();
114         stud.setStudId(2);
115         stud.setName("studddd_"+ts);
116         stud.setEmail("studddd_"+ts+"@gmail.com");
117         Student student = studentService.updateStudent(stud);
118         assertNotNull(student);
119         assertEquals("studddd_"+ts, student.getName());
120         assertEquals("studddd_"+ts+"@gmail.com", student.getEmail());
121         assertEquals(new Integer(2), student.getStudId());
122         
123         System.out.println("UpdatedStudent: "+student);
124     }
125 
126     @Test
127     public void testDeleteStudent() {
128         boolean deleted = studentService.deleteStudent(3);
129         assertTrue(deleted);
130         System.err.println("deleteStudent:"+deleted);
131     }
132 
133     @Test
134     public void testFindStudentMapById() {
135         Map studentMap = studentService.findStudentMapById(1);
136         System.err.println(studentMap);
137     }
138 
139     @Test
140     public void testFindAllStudentsMap() {
141         List> studentMapList = studentService.findAllStudentsMap();
142         for(Map studentMap : studentMapList)
143         {
144             System.out.println("id :"+studentMap.get("id"));
145             System.out.println("name :"+studentMap.get("name"));
146             System.out.println("email :"+studentMap.get("email"));
147             System.out.println("phone :"+studentMap.get("phone"));
148         }
149     }
150 
151 }

 

 1 package com.mybatis3.services;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import java.util.List;
 6 
 7 import org.junit.BeforeClass;
 8 import org.junit.Test;
 9 import org.junit.runner.RunWith;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.test.context.ContextConfiguration;
12 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13 
14 import com.mybatis3.domain.Tutor;
15 
16 @RunWith(SpringJUnit4ClassRunner.class)
17 @ContextConfiguration(locations="classpath:applicationContext.xml")
18 public class TutorServiceTest 
19 {
20     @Autowired
21     private TutorService tutorService;
22     
23     @BeforeClass
24     public static void setup() {
25         TestDataPopulator.initDatabase();
26     }
27 
28     
29     @Test
30     public void testFindAllTutors() {
31         List tutors = tutorService.findAllTutors();
32         assertNotNull(tutors);
33         for (Tutor tutor : tutors)
34         {
35             System.err.println(tutor);
36         }
37     }
38 
39     @Test
40     public void testFindTutorById() {
41         Tutor tutor = tutorService.findTutorById(1);
42         assertNotNull(tutor);
43         //System.err.println(tutor);
44     }
45 
46     @Test
47     public void testFindTutorByNameAndEmail() {
48         Tutor tutor = tutorService.findTutorByNameAndEmail("Paul", "[email protected]");
49         assertNotNull(tutor);
50         //System.err.println(tutor);
51     }
52 
53     @Test
54     public void testCreateTutor() {
55         Tutor tutor = new Tutor();
56         tutor.setName("siva");
57         tutor.setEmail("[email protected]");
58         tutor = tutorService.createTutor(tutor);
59         assertNotNull(tutor);
60     }
61 
62     @Test
63     public void testUpdateTutor() {
64         Tutor tutor = new Tutor();
65         tutor.setTutorId(1);
66         tutor.setName("sivaprasad");
67         tutor.setEmail("[email protected]");
68         tutor = tutorService.updateTutor(tutor);
69         Tutor updTutor = tutorService.findTutorById(1);
70         assertNotNull(updTutor);
71         System.err.println(updTutor);
72     }
73 
74     @Test
75     public void testDeleteTutor() {
76         boolean deleted = tutorService.deleteTutor(4);
77            assertTrue(deleted);
78     }
79 
80     @Test
81     public void testSelectTutorById() {
82         Tutor tutor = tutorService.selectTutorById(1);
83         assertNotNull(tutor);
84         System.err.println(tutor);
85     }
86 
87     @Test
88     public void testSelectTutorWithCoursesById() {
89         Tutor tutor = tutorService.selectTutorWithCoursesById(1);
90         assertNotNull(tutor);
91         System.err.println(tutor);
92     }
93 
94 }

 

转载于:https://www.cnblogs.com/shamgod/p/5442973.html

你可能感兴趣的:(java,数据库)