Mybatis入门例子

Mybatis 是轻量级的持久化框架,的确上手非常快.

Mybatis 大体上的思路就是由一个总的 config 文件配置全局的信息,比如 mysql 连接信息等。然后再 mapper 中指定查询的 sql,以及参数和返回值。

在 Service 中直接调用这个 mapper 即可。

依赖的 jar 包

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.22</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>RELEASE</version>
</dependency>

主要的 mybatis 配置文件

<?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>
    <!-- 配置类别名 -->
    <typeAliases>
        <typeAlias alias="Student" type="mybatis.Student"/>
    </typeAliases>
    <!-- 配置 mysql 连接 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.56.101:3306/mysql"/>
                <property name="username" value="root"/>
                <property name="password" value="123qwe"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置 mapper -->
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

创建 SqlSession 工厂

public class MyBatisSqlSessionFactory {
    private static SqlSessionFactory sqlSessionFactory;
    public static SqlSessionFactory getSqlSessionFactory(){
        if(sqlSessionFactory == null){
            InputStream inputStream;
            try{
                inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }catch (IOException e){
                System.out.println(e.getMessage());
            }
        }
        return sqlSessionFactory;
    }
    public static SqlSession openSession(){
        return getSqlSessionFactory().openSession();
    }
}

创建 Student 类:

public class Student {
    private Integer studId;
    private String name;
    private String email;
    private Date dob;
<span class="hljs-keyword">public</span> <span class="hljs-title class_">Integer</span> <span class="hljs-title function_">getStudId</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> studId;
}

<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">setStudId</span>(<span class="hljs-params">Integer studId</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">studId</span> = studId;
}

<span class="hljs-keyword">public</span> <span class="hljs-title class_">String</span> <span class="hljs-title function_">getName</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> name;
}

<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">setName</span>(<span class="hljs-params"><span class="hljs-built_in">String</span> name</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">name</span> = name;
}

<span class="hljs-keyword">public</span> <span class="hljs-title class_">String</span> <span class="hljs-title function_">getEmail</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> email;
}

<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">setEmail</span>(<span class="hljs-params"><span class="hljs-built_in">String</span> email</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">email</span> = email;
}

<span class="hljs-keyword">public</span> <span class="hljs-title class_">Date</span> <span class="hljs-title function_">getDob</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> dob;
}

<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">setDob</span>(<span class="hljs-params"><span class="hljs-built_in">Date</span> dob</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">dob</span> = dob;
}

}

创建 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="mybatis.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=#{ID}
    </select>
    <insert id="insertStudent" parameterType="Student">
        INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
    </insert>
</mapper>

创建 Mapper 接口

public interface StudentMapper {
    List<Student> findAllStudents();
    Student findStudentById(Integer id);
    void insertStudent(Student student);
}

创建服务类和测试类

public class StudentService {
    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){
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            return studentMapper.findStudentById(studId);
        }finally {
            sqlSession.close();
        }
    }
    public void createStudent(Student student){
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            studentMapper.insertStudent(student);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }
}

单元测试类

public class StudentServiceTest {
    private static StudentService studentService;
<span class="hljs-meta">@BeforeClass</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">setup</span>(<span class="hljs-params"></span>){
    studentService = <span class="hljs-keyword">new</span> mybatis.<span class="hljs-title class_">StudentService</span>();
}

<span class="hljs-meta">@AfterClass</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">teardown</span>(<span class="hljs-params"></span>){
    studentService = <span class="hljs-literal">null</span>;
}

<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">testFindAllStudents</span>(<span class="hljs-params"></span>){
    <span class="hljs-title class_">List</span>&lt;<span class="hljs-title class_">Student</span>&gt; students = studentService.<span class="hljs-title function_">findAllStudents</span>();
    <span class="hljs-title class_">Assert</span>.<span class="hljs-title function_">assertNotNull</span>(students);
    <span class="hljs-keyword">for</span>(<span class="hljs-title class_">Student</span> <span class="hljs-attr">student</span>:students){
        <span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(student);
    }
}

<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">testFindStudentById</span>(<span class="hljs-params"></span>){
    <span class="hljs-title class_">Student</span> student = studentService.<span class="hljs-title function_">findStudentById</span>(<span class="hljs-number">1</span>);
    <span class="hljs-title class_">Assert</span>.<span class="hljs-title function_">assertNotNull</span>(student);
    <span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(student);
}

<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">testCreateStudent</span>(<span class="hljs-params"></span>){
    <span class="hljs-title class_">Student</span> student = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>();
    student.<span class="hljs-title function_">setStudId</span>(<span class="hljs-number">3</span>);
    student.<span class="hljs-title function_">setName</span>(<span class="hljs-string">"student_"</span>+<span class="hljs-number">3</span>);
    student.<span class="hljs-title function_">setEmail</span>(<span class="hljs-string">"student_"</span>+<span class="hljs-number">3</span>+<span class="hljs-string">"@email.com"</span>);
    student.<span class="hljs-title function_">setDob</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());
    studentService.<span class="hljs-title function_">createStudent</span>(student);
    <span class="hljs-title class_">Student</span> newStudent = studentService.<span class="hljs-title function_">findStudentById</span>(<span class="hljs-number">3</span>);
    <span class="hljs-title class_">Assert</span>.<span class="hljs-title function_">assertNotNull</span>(newStudent);
}

}

数据库脚本

create table STUDENTS(
stud_id int(11) not null auto_increment,
name varchar(50) not null,
email varchar(50) not null,
dob date default null,
primary key(stud_id)
);
insert into STUDENTS(stud_id,name,email,dob) values(1,"student1","student1@email.com","1999-08-08");
insert into STUDENTS(stud_id,name,email,dob) values(2,"student2","student2@email.com","2000-01-01");
select * from STUDENTS;