一、
1.Mapper
1 /** 2 * 3 */ 4 package com.mybatis3.mappers; 5 6 import org.apache.ibatis.annotations.Select; 7 8 import com.mybatis3.domain.Address; 9 10 /** 11 * @author Siva 12 * 13 */ 14 public interface AddressMapper 15 { 16 @Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}") 17 Address selectAddressById(int id); 18 }
1 package com.mybatis3.mappers; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import org.apache.ibatis.annotations.Delete; 7 import org.apache.ibatis.annotations.Insert; 8 import org.apache.ibatis.annotations.Options; 9 import org.apache.ibatis.annotations.Result; 10 import org.apache.ibatis.annotations.ResultMap; 11 import org.apache.ibatis.annotations.Results; 12 import org.apache.ibatis.annotations.Select; 13 import org.apache.ibatis.annotations.Update; 14 15 import com.mybatis3.domain.Student; 16 17 18 19 /** 20 * @author Siva 21 * 22 */ 23 public interface StudentMapper 24 { 25 26 @Select("select * from students") 27 @Results({ 28 @Result(id=true, column="stud_id", property="studId"), 29 @Result(column="name", property="name"), 30 @Result(column="email", property="email"), 31 @Result(column="addr_id", property="address.addrId") 32 }) 33 List<Student> findAllStudents(); 34 35 @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students") 36 List<Map<String,Object>> findAllStudentsMap(); 37 38 @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}") 39 Student findStudentById(Integer id); 40 41 @Select("select stud_id as studId, name, email, addr_id as 'address.addrId', phone from students where stud_id=#{id}") 42 Map<String,Object> findStudentMapById(Integer id); 43 44 @Select("select stud_id, name, email, a.addr_id, street, city, state, zip, country"+ 45 " FROM students s left outer join addresses a on s.addr_id=a.addr_id"+ 46 " where stud_id=#{studId} ") 47 @ResultMap("com.mybatis3.mappers.StudentMapper.StudentWithAddressResult") 48 Student selectStudentWithAddress(int studId); 49 50 @Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})") 51 @Options(useGeneratedKeys=true, keyProperty="studId") 52 void insertStudent(Student student); 53 54 @Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addrId},#{phone})") 55 @Options(useGeneratedKeys=true, keyProperty="studId") 56 void insertStudentWithMap(Map<String, Object> map); 57 58 @Update("update students set name=#{name}, email=#{email}, phone=#{phone} where stud_id=#{studId}") 59 void updateStudent(Student student); 60 61 @Delete("delete from students where stud_id=#{studId}") 62 int deleteStudent(int studId); 63 64 }
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<Course> 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<Tutor> 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 /** 2 * 3 */ 4 package com.mybatis3.services; 5 6 import java.util.List; 7 8 import org.apache.ibatis.session.SqlSession; 9 10 import com.mybatis3.domain.Tutor; 11 import com.mybatis3.mappers.TutorMapper; 12 import com.mybatis3.util.MyBatisUtil; 13 14 15 /** 16 * @author Siva 17 * 18 */ 19 20 public class TutorService 21 { 22 public List<Tutor> findAllTutors() 23 { 24 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 25 try { 26 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 27 return mapper.findAllTutors(); 28 } finally { 29 sqlSession.close(); 30 } 31 } 32 33 public Tutor findTutorById(int tutorId) 34 { 35 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 36 try { 37 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 38 return mapper.findTutorById(tutorId); 39 } finally { 40 sqlSession.close(); 41 } 42 } 43 44 public Tutor findTutorByNameAndEmail(String name, String email) 45 { 46 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 47 try { 48 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 49 return mapper.findTutorByNameAndEmail(name, email); 50 } finally { 51 sqlSession.close(); 52 } 53 } 54 55 public Tutor createTutor(Tutor tutor) 56 { 57 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 58 try { 59 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 60 mapper.insertTutor(tutor); 61 sqlSession.commit(); 62 } finally { 63 sqlSession.close(); 64 } 65 return tutor; 66 } 67 68 public Tutor updateTutor(Tutor tutor) 69 { 70 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 71 try { 72 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 73 mapper.updateTutor(tutor); 74 sqlSession.commit(); 75 } finally { 76 sqlSession.close(); 77 } 78 return tutor; 79 } 80 81 public boolean deleteTutor(int tutorId) 82 { 83 boolean deleted = false; 84 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 85 try { 86 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 87 int nor = mapper.deleteTutor(tutorId); 88 deleted = (nor == 1); 89 sqlSession.commit(); 90 } finally { 91 sqlSession.close(); 92 } 93 return deleted; 94 } 95 96 public Tutor selectTutorById(int tutorId) 97 { 98 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 99 try { 100 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 101 return mapper.selectTutorById(tutorId); 102 } finally { 103 sqlSession.close(); 104 } 105 } 106 107 public Tutor selectTutorWithCoursesById(int tutorId) { 108 SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession(); 109 try { 110 TutorMapper mapper = sqlSession.getMapper(TutorMapper.class); 111 return mapper.selectTutorWithCoursesById(tutorId); 112 } 113 114 finally { 115 sqlSession.close(); 116 } 117 } 118 }
3.Domain
4.辅助类
1 /** 2 * 3 */ 4 package com.mybatis3.sqlproviders; 5 6 7 import java.util.Map; 8 9 import org.apache.ibatis.jdbc.SQL; 10 11 import com.mybatis3.domain.Tutor; 12 /** 13 * @author Siva 14 * 15 */ 16 public class TutorDynaSqlProvider 17 { 18 19 public String findAllTutorsSql() 20 { 21 return new SQL() {{ 22 SELECT("tutor_id as tutorId, name, email"); 23 FROM("tutors"); 24 }}.toString(); 25 } 26 27 public String findTutorByIdSql(final int tutorId) 28 { 29 /*return new SQL() {{ 30 SELECT("tutor_id as tutorId, name, email"); 31 FROM("tutors"); 32 WHERE("tutor_id = #{tutorId}"); 33 }}.toString();*/ 34 35 return new SQL() {{ 36 SELECT("tutor_id as tutorId, name, email"); 37 FROM("tutors"); 38 WHERE("tutor_id="+tutorId); 39 }}.toString(); 40 } 41 42 43 public String findTutorByNameAndEmailSql(Map<String, Object> map) 44 { 45 String name = (String) map.get("name"); 46 String email = (String) map.get("email"); 47 System.err.println(name+":"+email); 48 49 return new SQL() {{ 50 SELECT("tutor_id as tutorId, name, email"); 51 FROM("tutors"); 52 WHERE("name=#{name} AND email=#{email}"); 53 }}.toString(); 54 } 55 56 public String insertTutor(final Tutor tutor) { 57 58 return new SQL() {{ 59 INSERT_INTO("TUTORS"); 60 61 if (tutor.getName() != null) { 62 VALUES("NAME", "#{name}"); 63 } 64 65 if (tutor.getEmail() != null) { 66 VALUES("EMAIL", "#{email}"); 67 } 68 }}.toString(); 69 70 } 71 72 public String updateTutor(final Tutor tutor) 73 { 74 75 return new SQL() {{ 76 UPDATE("TUTORS"); 77 78 if (tutor.getName() != null) { 79 SET("NAME = #{name}"); 80 } 81 82 if (tutor.getEmail() != null) { 83 SET("EMAIL = #{email}"); 84 } 85 WHERE("TUTOR_ID = #{tutorId}"); 86 }}.toString(); 87 } 88 89 public String deleteTutor(int tutorId) 90 { 91 92 return new SQL() {{ 93 DELETE_FROM("TUTORS"); 94 WHERE("TUTOR_ID = #{tutorId}"); 95 }}.toString(); 96 97 } 98 99 public String selectTutorById() 100 { 101 return new SQL() {{ 102 SELECT("t.tutor_id, t.name as tutor_name, email"); 103 SELECT("a.addr_id, street, city, state, zip, country"); 104 SELECT("course_id, c.name as course_name, description, start_date, end_date"); 105 FROM("TUTORS t"); 106 LEFT_OUTER_JOIN("addresses a on t.addr_id=a.addr_id"); 107 LEFT_OUTER_JOIN("courses c on t.tutor_id=c.tutor_id"); 108 WHERE("t.TUTOR_ID = #{id}"); 109 }}.toString(); 110 111 112 } 113 }
5.配置及资源文件
(1)mybatis-config.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 7 <properties resource="application.properties"/> 8 9 <typeAliases> 10 <package name="com.mybatis3.domain"/> 11 </typeAliases> 12 <typeHandlers> 13 <typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/> 14 </typeHandlers> 15 16 <environments default="development"> 17 <environment id="development"> 18 <transactionManager type="JDBC"/> 19 <dataSource type="POOLED"> 20 <property name="driver" value="${jdbc.driverClassName}"/> 21 <property name="url" value="${jdbc.url}"/> 22 <property name="username" value="${jdbc.username}"/> 23 <property name="password" value="${jdbc.password}"/> 24 </dataSource> 25 </environment> 26 </environments> 27 28 <mappers> 29 <package name="com.mybatis3.mappers"/> 30 </mappers> 31 32 </configuration>
(2)StudentMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 6 <mapper namespace="com.mybatis3.mappers.StudentMapper"> 7 8 9 <resultMap type="Address" id="AddressResult"> 10 <id property="addrId" column="addr_id"/> 11 <result property="street" column="street"/> 12 <result property="city" column="city"/> 13 <result property="state" column="state"/> 14 <result property="zip" column="zip"/> 15 <result property="country" column="country"/> 16 </resultMap> 17 18 <resultMap type="Student" id="StudentWithAddressResult"> 19 <id property="studId" column="stud_id"/> 20 <result property="name" column="name"/> 21 <result property="email" column="email"/> 22 <association property="address" resultMap="AddressResult"/> 23 </resultMap> 24 25 26 </mapper>
(3)TutorMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 6 <mapper namespace="com.mybatis3.mappers.TutorMapper"> 7 8 <resultMap type="Address" id="AddressResult"> 9 <id property="addrId" column="addr_id"/> 10 <result property="street" column="street"/> 11 <result property="city" column="city"/> 12 <result property="state" column="state"/> 13 <result property="zip" column="zip"/> 14 <result property="country" column="country"/> 15 </resultMap> 16 17 <resultMap type="Course" id="CourseResult"> 18 <id column="course_id" property="courseId"/> 19 <result column="course_name" property="name"/> 20 <result column="description" property="description"/> 21 <result column="start_date" property="startDate"/> 22 <result column="end_date" property="endDate"/> 23 </resultMap> 24 25 <resultMap type="Tutor" id="TutorResult"> 26 <id column="tutor_id" property="tutorId"/> 27 <result column="tutor_name" property="name"/> 28 <result column="email" property="email"/> 29 <association property="address" resultMap="AddressResult"/> 30 <collection property="courses" resultMap="CourseResult"></collection> 31 </resultMap> 32 33 </mapper>
6.测试文件
1 package com.mybatis3.services; 2 3 import static org.junit.Assert.*; 4 5 import java.util.List; 6 7 import org.junit.AfterClass; 8 import org.junit.BeforeClass; 9 import org.junit.Test; 10 11 import com.mybatis3.domain.Tutor; 12 13 public class TutorServiceTest 14 { 15 16 private static TutorService tutorService; 17 18 @BeforeClass 19 public static void setup() { 20 tutorService = new TutorService(); 21 TestDataPopulator.initDatabase(); 22 } 23 24 @AfterClass 25 public static void teardown() { 26 tutorService = null; 27 } 28 29 @Test 30 public void testFindAllTutors() { 31 List<Tutor> 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", "paul@gmail.com"); 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("siva@gmail.com"); 58 tutor = tutorService.createTutor(tutor); 59 assertNotNull(tutor); 60 System.err.println(tutor.getTutorId()); 61 } 62 63 @Test 64 public void testUpdateTutor() { 65 Tutor tutor = new Tutor(); 66 tutor.setTutorId(1); 67 tutor.setName("sivaprasad"); 68 tutor.setEmail("sivaprasad@gmail.com"); 69 tutor = tutorService.updateTutor(tutor); 70 Tutor updTutor = tutorService.findTutorById(1); 71 assertNotNull(updTutor); 72 System.err.println(updTutor); 73 } 74 75 @Test 76 public void testDeleteTutor() { 77 boolean deleted = tutorService.deleteTutor(4); 78 assertTrue(deleted); 79 } 80 81 @Test 82 public void testSelectTutorById() { 83 Tutor tutor = tutorService.selectTutorById(1); 84 assertNotNull(tutor); 85 System.err.println(tutor); 86 } 87 88 @Test 89 public void testSelectTutorWithCoursesById() { 90 Tutor tutor = tutorService.selectTutorWithCoursesById(1); 91 assertNotNull(tutor); 92 System.err.println(tutor); 93 } 94 95 }