MyBatis学习笔记

1、工程搭建:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.emmaluo.mbatislearning</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- 无集成spring -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <!-- 集成spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.0.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>


    </dependencies>


</project>

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="jdbc.properties">

    </properties>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>

    </settings>

    <typeAliases>
        <package name="com.emmaluo.mybatislearning.model" />
    </typeAliases>

    <typeHandlers>
        <typeHandler handler="com.emmaluo.mybatislearning.typehandler.PhoneTypeHandler" />
        <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.emmaluo.mybatislearning.model.Gender" />
    </typeHandlers>


    <!-- Continue going here -->
    <environments default="development">
        <environment id="development">

            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <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/emmaluo/mybatislearning/mapper/StudentMapper.xml"/>
        <mapper resource="com/emmaluo/mybatislearning/mapper/TutorMapper.xml" />
        <mapper resource="com/emmaluo/mybatislearning/mapper/UserPicMapper.xml" />
        <mapper resource="com/emmaluo/mybatislearning/mapper/CourseMapper.xml" />
    </mappers>

</configuration>

知识点包括:environments default environment dataSource mappers mapper typeAliases                                  typeAliase typeHandlers typeHandler

jdbc.propertis

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/stock
jdbc.username=stock
jdbc.password=password

log4j.properties

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n

log4j.logger.com.mybatis3=DEBUG

相关表的SQL文件

/*
MySQL Backup
Source Server Version: 5.7.12
Source Database: stock
Date: 2016/6/27 16:07:05
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
--  Table structure for `addresses`
-- ----------------------------
DROP TABLE IF EXISTS `addresses`;
CREATE TABLE `addresses` (
  `ADDR_ID` int(11) NOT NULL AUTO_INCREMENT,
  `STREET` varchar(50) NOT NULL,
  `CITY` varchar(50) NOT NULL,
  `STATE` varchar(50) NOT NULL,
  `ZIP` varchar(10) DEFAULT NULL,
  `COUNTRY` varchar(50) NOT NULL,
  PRIMARY KEY (`ADDR_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Table structure for `courses`
-- ----------------------------
DROP TABLE IF EXISTS `courses`;
CREATE TABLE `courses` (
  `COURSE_ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(100) NOT NULL,
  `DESCRIPTION` varchar(512) DEFAULT NULL,
  `START_DATE` date DEFAULT NULL,
  `END_DATE` date DEFAULT NULL,
  `TUTOR_ID` int(11) NOT NULL,
  PRIMARY KEY (`COURSE_ID`),
  KEY `FK_COURSE_TUTOR` (`TUTOR_ID`),
  CONSTRAINT `FK_COURSE_TUTOR` FOREIGN KEY (`TUTOR_ID`) REFERENCES `tutors` (`TUTOR_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Table structure for `course_enrollment`
-- ----------------------------
DROP TABLE IF EXISTS `course_enrollment`;
CREATE TABLE `course_enrollment` (
  `COURSE_ID` int(11) NOT NULL,
  `STUD_ID` int(11) NOT NULL,
  PRIMARY KEY (`COURSE_ID`,`STUD_ID`),
  KEY `FK_ENROLLMENT_STUD` (`STUD_ID`),
  CONSTRAINT `FK_ENROLLMENT_COURSE` FOREIGN KEY (`COURSE_ID`) REFERENCES `courses` (`COURSE_ID`),
  CONSTRAINT `FK_ENROLLMENT_STUD` FOREIGN KEY (`STUD_ID`) REFERENCES `students` (`STUD_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
--  Table structure for `students`
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
  `STUD_ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(50) NOT NULL,
  `EMAIL` varchar(50) NOT NULL,
  `PHONE` varchar(15) DEFAULT NULL,
  `DOB` date DEFAULT NULL,
  `BIO` longtext,
  `PIC` blob,
  `ADDR_ID` int(11) DEFAULT NULL,
  `GENDER` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`STUD_ID`),
  KEY `FK_STUDENTS_ADDR` (`ADDR_ID`),
  CONSTRAINT `FK_STUDENTS_ADDR` FOREIGN KEY (`ADDR_ID`) REFERENCES `addresses` (`ADDR_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Table structure for `tutors`
-- ----------------------------
DROP TABLE IF EXISTS `tutors`;
CREATE TABLE `tutors` (
  `TUTOR_ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(50) NOT NULL,
  `EMAIL` varchar(50) NOT NULL,
  `PHONE` varchar(15) DEFAULT NULL,
  `DOB` date DEFAULT NULL,
  `BIO` longtext,
  `PIC` blob,
  `ADDR_ID` int(11) DEFAULT NULL,
  PRIMARY KEY (`TUTOR_ID`),
  KEY `FK_TUTORS_ADDR` (`ADDR_ID`),
  CONSTRAINT `FK_TUTORS_ADDR` FOREIGN KEY (`ADDR_ID`) REFERENCES `addresses` (`ADDR_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Table structure for `user_pics`
-- ----------------------------
DROP TABLE IF EXISTS `user_pics`;
CREATE TABLE `user_pics` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(50) DEFAULT NULL,
  `PIC` blob,
  `BIO` longtext,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Records 
-- ----------------------------
INSERT INTO `addresses` VALUES ('1','4891 Pacific Hwy','San Diego','CA','92110','San Diego'), ('2','2400 N Jefferson St','Perry','FL','32347','Taylor'), ('3','710 N Cable Rd','Lima','OH','45825','Allen'), ('4','5108 W Gore Blvd','Lawton','OK','32365','Comanche');
INSERT INTO `courses` VALUES ('1','Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15','1'), ('2','Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30','1'), ('3','MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15','2');
INSERT INTO `course_enrollment` VALUES ('1','1'), ('1','2'), ('2','2');
INSERT INTO `students` VALUES ('1','Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,'3',NULL), ('2','Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,'4',NULL), ('42','student_3','student_3@gmail.com','123-123-1239',NULL,NULL,NULL,NULL,'0'), ('43','student_3','student_3@gmail.com','123-123-1239',NULL,NULL,NULL,NULL,'0'), ('44','student_3','student_3@gmail.com','123-123-1239',NULL,NULL,NULL,NULL,'0'), ('55','stud_1466947477396','stud_1466947477396@gmail.com',NULL,NULL,NULL,NULL,NULL,NULL), ('61','stud_1466947633475','stud_1466947633475@gmail.com',NULL,NULL,NULL,NULL,NULL,NULL), ('62','stud_1466949446311','stud_1466949446311@gmail.com',NULL,NULL,NULL,NULL,NULL,NULL), ('63','stud_1467014304497','stud_1467014304497@gmail.com',NULL,NULL,NULL,NULL,NULL,NULL);
INSERT INTO `tutors` VALUES ('1','John','john@gmail.com','111-222-3333','1980-05-20',NULL,NULL,'1'), ('2','Paul','paul@gmail.com','123-321-4444','1981-03-15',NULL,NULL,'2');

2、包结构:

 

表映射的JAVA对象

 

Mapper接口

 

service包

 

typehandler与model包中的PhoneNumber关系

 

test包与service包关系

 

工程UML关系全图

 

3、查询、插入、更新mapper的xml文件配置

创建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.emmaluo.mybatislearning.IDAO.StudentMapper">
    <resultMap id="AddressResult" type="Address">
        <id property="addrId" column="addr_id" />
        <result property="street" column="street" />
        <result property="city" column="city" />
        <result property="state" column="state" />
        <result property="zip" column="zip" />
        <result property="country" column="country" />
    </resultMap>


    <resultMap id="StudentResult" type="Student">
        <id property="studId" column="stud_id"/>
        <result property="name" column="name"/>
        <result property="email" column="email"/>
        <result property="dob" column="dob"/>
    </resultMap>
    <resultMap id="StudentWithAddressResult" type="Student" >
        <id property="studId" column="stud_id"/>
        <result property="name" column="name"/>
        <result property="email" column="email"/>
        <result property="dob" column="dob"/>
        <result property="gender" column="gender" />
        <result property="phone" column="phone" javaType="PhoneNumber" jdbcType="VARCHAR" typeHandler="com.emmaluo.mybatislearning.typehandler.PhoneTypeHandler" />
        <association property="address" resultMap="AddressResult" />
    </resultMap>
    <select id="selectStudentWithAddress" parameterType="int" resultMap="StudentWithAddressResult">
        SELECT STUD_ID, NAME, EMAIL, PHONE,dob, A.ADDR_ID, STREET, CITY,
                STATE, ZIP, COUNTRY
        FROM STUDENTS S LEFT OUTER JOIN ADDRESSES A ON
              S.ADDR_ID=A.ADDR_ID
        WHERE STUD_ID=#{studId}
    </select>
    <select id="findAllStudents" resultMap="StudentResult">
        SELECT * from students
    </select>
    <select id="findStudentById" parameterType="int" resultType="Student">
        SELECT STUD_ID as studId,NAME,EMAIL,DOB,PHONE,gender
        FROM STUDENTS WHERE STUD_ID=#{id}
    </select>
    <select id="findAllStudentsByNameEmail" resultMap="StudentWithAddressResult">
        SELECT STUD_ID,NAME,EMAIL,DOB,PHONE,gender
        FROM STUDENTS WHERE name = #{param1} and email=#{param2}
    </select>
    <insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
        insert into students(name,email,dob)
        values(#{name},#{email},#{dob})
    </insert>
    <insert id="insertStudentWithPhone" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
        insert into students(name,email,dob,PHONE)
        values(#{name},#{email},#{dob},#{phone})
    </insert>
    <insert id="insertStudentWithGender" parameterType="Student"
            useGeneratedKeys="true" keyProperty="studId">
        insert into students(name,email,addr_id, phone,gender)
        values(#{name},#{email},#{address.addrId},#{phone},#{gender})
    </insert>
    <delete id="deleteStudentById" parameterType="int">
        DELETE FROM students
        WHERE stud_id=#{id}
    </delete>
    <update id="updateStudent" parameterType="Student">
        update students
        <set>
            <if test="name != null">name=#{name},</if>
            <if test="email != null">email=#{email},</if>

        </set>
        where stud_id=#{studId}
    </update>
</mapper>

知识点包括:mapper namespace属性(值为mapper接口全限定名) select parameteType resultType resultMap insert useGenerateKeys keyProperty selectKey keyProperty resultType order update parameterType delete parameterType association collection property column select

4、数据查询接口层

Mapper接口

package com.emmaluo.mybatislearning.IDAO;

import com.emmaluo.mybatislearning.model.Student;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;


import java.util.List;

/**
 * Created by zcluo on 2016/6/23.
 */
@Component
public interface StudentMapper {
    List<Student> findAllStudents(RowBounds rowBounds);
    List<Student> findAllStudents();
    List<Student> findAllStudentsByNameEmail(String name,String email);
    Student findStudentById(Integer id);
    int insertStudent(Student student);
    int insertStudentWithPhone(Student student);
    int insertStudentWithGender(Student student);
    int deleteStudentById(Integer id);
    Student selectStudentWithAddress(Integer studId);
    int updateStudent(Student student);

}

5、服务层

服务实现

package com.emmaluo.mybatislearning.service;


import com.emmaluo.mybatislearning.IDAO.StudentMapper;
import com.emmaluo.mybatislearning.model.Student;

import com.emmaluo.mybatislearning.util.MyBatisSqlSessionFactory;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by zcluo on 2016/6/23.
 */
public class StudentService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    public List<Student> findAllStudents(){
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findAllStudents();
        }
        finally {
            sqlSession.close();
        }
    }

    public Student findStudentById(Integer studId){
        logger.debug("Select Student By ID :{}",studId);
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findStudentById(studId);
        }
        finally {
            sqlSession.close();
        }
    }

    public Student findStudentWithAddress(Integer studId){
        logger.debug("Select Student By ID :{}",studId);
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.selectStudentWithAddress(studId);
        }
        finally {
            sqlSession.close();
        }
    }

    public List<Student> findStudentsWithNameAndEmail(String name,String email){
        logger.debug("Select Student by Name: {} and Email: {}",name,email);
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findAllStudentsByNameEmail(name,email);
        }
        finally {
            sqlSession.close();
        }
    }

    public List<Student> findStudentsAllWithPagenation(int offset,int limits){
        logger.debug("Select Student All with Pagenation!");
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            RowBounds rowBounds = new RowBounds(offset,limits);
            return studentMapper.findAllStudents(rowBounds);
        }
        finally {
            sqlSession.close();
        }
    }



    public int  createStudent(Student student) {
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        int insertRows = 0;
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            insertRows = studentMapper.insertStudent(student);
            sqlSession.commit();

        } finally {
            sqlSession.close();
            return insertRows;
        }
    }

    public int insertStudentWithPhone(Student student){
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        int insertRows = 0;
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            insertRows = studentMapper.insertStudentWithPhone(student);
            sqlSession.commit();

        } finally {
            sqlSession.close();
            return insertRows;
        }
    }

    public int insertStudentWithGender(Student student){
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        int insertRows = 0;
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            insertRows = studentMapper.insertStudentWithGender(student);
            sqlSession.commit();

        } finally {
            sqlSession.close();
            return insertRows;
        }
    }

    public int deleteStudentById(Integer studId) {
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        int deleteRows = 0;
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            deleteRows = studentMapper.deleteStudentById(studId);
            sqlSession.commit();
        } finally {
            sqlSession.close();
            return deleteRows;
        }
    }

    public int updateStudent(Student student) {
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        int updateRows = 0;
        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            updateRows = studentMapper.updateStudent(student);
            sqlSession.commit();
        }
        finally {
            sqlSession.close();
            return updateRows;
        }
    }
}

6、测试

测试案例

package com.emmaluo.mybatislearning.test;

import com.emmaluo.mybatislearning.model.Gender;
import com.emmaluo.mybatislearning.model.PhoneNumber;
import com.emmaluo.mybatislearning.model.Student;

import com.emmaluo.mybatislearning.service.StudentService;
import org.apache.ibatis.session.RowBounds;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;
import java.util.List;



/**
 * Created by zcluo on 2016/6/23.
 */
public class StudentServiceTest {



    private static StudentService studentService;
    @Before
    public void setUp() throws Exception {

        studentService = new StudentService();

    }

    @After
    public void tearDown() throws Exception {

        studentService = null;
    }

    @Test
    public void findAllStudents() throws Exception {

        List<Student> students = studentService.findAllStudents();
        Assert.assertNotNull(students);
        for(Student student : students){
            System.out.println(student);
        }

    }

    @Test
    public void findStudentsAllWithPagenation() throws Exception {

        int offset=0;
        int limits=2;
        List<Student> students = studentService.findStudentsAllWithPagenation(offset,limits);
        Assert.assertNotNull(students);
        Assert.assertTrue(students.size()<=limits);
        for(Student student : students){
            System.out.println(student);
        }
    }

    @Test
    public void findStudentById() throws Exception {

        Student student = studentService.findStudentById(1);
        Assert.assertNotNull(student);
        System.out.println(student);
    }

    @Test
    public void findStudentsWithNameAndEmail() throws Exception {

        List<Student> students = studentService.findStudentsWithNameAndEmail("student_3","student_3@gmail.com");
        Assert.assertNotNull(students);
        System.out.println(students);

    }

    @Test
    public void findStudentWithAddress() throws Exception {

        Student student = studentService.findStudentWithAddress(1);
        Assert.assertNotNull(student);
        System.out.println(student);

    }



    @Test
    public void createStudent() throws Exception {
        Student student = new Student();
        int id = 3;
        //student.setStudId(id);
        student.setName("student_"+id);
        student.setEmail("student_"+id+"@gmail.com");
        student.setDob(new Date());
        int rowInserted = studentService.createStudent(student);
        id = student.getStudId();
        Student newStudent = studentService.findStudentById(id);
        Assert.assertNotNull(newStudent);
        Assert.assertEquals(1,rowInserted);
        System.out.println(newStudent);
        studentService.deleteStudentById(id);

    }

    @Test
    public void insertStudentWithPhone() throws Exception {

        Student student = new Student();
        int id = 3;
        //student.setStudId(id);
        student.setName("student_"+id);
        student.setEmail("student_"+id+"@gmail.com");
        student.setDob(new Date());
        PhoneNumber phone = new PhoneNumber("123-123-1239");
        student.setPhone(phone);
        int rowInserted = studentService.insertStudentWithPhone(student);
        id = student.getStudId();
        Student newStudent = studentService.findStudentById(id);
        Assert.assertNotNull(newStudent);
        Assert.assertEquals(1,rowInserted);
        System.out.println(newStudent);
        studentService.deleteStudentById(id);
    }

    @Test
    public void insertStudentWithGender() throws Exception {

        Student student = new Student();
        int id = 3;
        //student.setStudId(id);
        student.setName("student_"+id);
        student.setEmail("student_"+id+"@gmail.com");
        student.setDob(new Date());
        PhoneNumber phone = new PhoneNumber("123-123-1239");
        student.setPhone(phone);
        Gender gender = Gender.FEMALE;
        student.setGender(gender);
        int rowInserted = studentService.insertStudentWithGender(student);
        id = student.getStudId();
        Student newStudent = studentService.findStudentById(id);
        Assert.assertNotNull(newStudent);
        Assert.assertEquals(1,rowInserted);
        System.out.println(newStudent);
        studentService.deleteStudentById(id);
    }

    @Test
    public void updateStudent() throws Exception {

        Student student = new Student();
        int id = 0;
        //student.setStudId(id);
        student.setName("student_"+id);
        student.setEmail("student_"+id+"@gmail.com");
        student.setDob(new Date());
        int rowInserted = studentService.createStudent(student);
        id = student.getStudId();
        student.setName("student_" + id);
        student.setEmail("student_"+id+"@gmail.com");
        int rowUpdated = studentService.updateStudent(student);
        Assert.assertEquals(1,rowUpdated);
        student = studentService.findStudentById(id);
        System.out.println(student);
        int rowDeleted = studentService.deleteStudentById(id);
        Assert.assertEquals(1,rowDeleted);

    }

    @Test
    public void deleteStudentById() throws Exception {
        Student student = new Student();
        int id = 3;
        //student.setStudId(id);
        student.setName("student_"+id);
        student.setEmail("student_"+id+"@gmail.com");
        student.setDob(new Date());
        studentService.createStudent(student);
        int rowdeleted = studentService.deleteStudentById(student.getStudId());
        Student s = studentService.findStudentById(student.getStudId());
        Assert.assertNull(s);
        Assert.assertEquals(1,rowdeleted);


    }



}

7、spring集成

spring配置文件

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.emmaluo" />
    <context:property-placeholder location="jdbc.properties" />
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.emmaluo.mybatislearning.IDAO" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </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="typeAliases"
                  value="com.emmaluo.mybatislearning.model.UserPic,com.emmaluo.mybatislearning.model.Tutor,com.emmaluo.mybatislearning.model.Course,com.emmaluo.mybatislearning.model.Address,com.emmaluo.mybatislearning.model.Student" />
        <property name="typeAliasesPackage" value="com.emmaluo.mybatislearning.model" />
        <!--
        <property name="typeHandlers" value="com.emmaluo.mybatislearning.typehandler.PhoneTypeHandler" />
        -->
        <property name="typeHandlersPackage" value="com.emmaluo.mybatislearning.typehandler" />
        <property name="mapperLocations" value="classpath*:com/emmaluo/**/*.xml" />
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

查询接口代码注解

package com.emmaluo.mybatislearning.IDAO;

import com.emmaluo.mybatislearning.model.Student;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;


import java.util.List;

/**
 * Created by zcluo on 2016/6/23.
 */
@Component
public interface StudentMapper {
    List<Student> findAllStudents(RowBounds rowBounds);
    List<Student> findAllStudents();
    List<Student> findAllStudentsByNameEmail(String name,String email);
    Student findStudentById(Integer id);
    int insertStudent(Student student);
    int insertStudentWithPhone(Student student);
    int insertStudentWithGender(Student student);
    int deleteStudentById(Integer id);
    Student selectStudentWithAddress(Integer studId);
    int updateStudent(Student student);

}

服务层代码注解

package com.emmaluo.mybatislearning.service;

import com.emmaluo.mybatislearning.IDAO.StudentMapper;
import com.emmaluo.mybatislearning.model.Student;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by zcluo on 2016/6/26.
 */
@Component
public class StudentServiceWithSpring {
    @Resource
    private StudentMapper studentMapper;

    public StudentMapper getStudentMapper() {
        return studentMapper;
    }

    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    public Student createStudent(Student student)
    {
        this.studentMapper.insertStudent(student);
        return student;
    }
}

测试案例

package com.emmaluo.mybatislearning.test;

import com.emmaluo.mybatislearning.model.Address;
import com.emmaluo.mybatislearning.model.Student;
import com.emmaluo.mybatislearning.service.StudentService;
import com.emmaluo.mybatislearning.service.StudentServiceWithSpring;
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 javax.annotation.Resource;

import static org.junit.Assert.*;

/**
 * Created by zcluo on 2016/6/26.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:mybatis-spring.xml")
public class StudentServiceSpringTest {
    @Resource
    private StudentServiceWithSpring studentServiceWithSpring;

    @Test
    public void testCreateStudent(){
        Address address = new Address(0, "Quaker Ridge Rd.", "Bethel", "Brooklyn", "06801", "USA");
        Student stud = new Student();
        long ts = System.currentTimeMillis();
        stud.setName("stud_" + ts);
        stud.setEmail("stud_" + ts + "@gmail.com");
        stud.setAddress(address);
        Student student = studentServiceWithSpring.createStudent(stud);
        assertNotNull(student);
        assertEquals("stud_" + ts, student.getName());
        assertEquals("stud_" + ts + "@gmail.com", student.getEmail());
        System.err.println("CreatedStudent: " + student);
    }


}

所有代码:https://github.com/zcluo/mybatislearning.git

参考书籍:《Java Persistence with MyBatis 3》、http://www.mybatis.org/mybatis-3/zh/index.html

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据