Mybatis入门例子

  1. 云栖社区>
  2. 博客>
  3. 正文

Mybatis入门例子

青夜之衫 2017-12-05 19:37:00 浏览450 评论0

摘要: Mybatis是轻量级的持久化框架,的确上手非常快. Mybatis大体上的思路就是由一个总的config文件配置全局的信息,比如mysql连接信息等。然后再mapper中指定查询的sql,以及参数和返回值。

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;

    public Integer getStudId() {
        return studId;
    }

    public void setStudId(Integer studId) {
        this.studId = studId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = 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;

    @BeforeClass
    public static void setup(){
        studentService = new mybatis.StudentService();
    }

    @AfterClass
    public static void teardown(){
        studentService = null;
    }

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

    @Test
    public void testFindStudentById(){
        Student student = studentService.findStudentById(1);
        Assert.assertNotNull(student);
        System.out.println(student);
    }

    @Test
    public void testCreateStudent(){
        Student student = new Student();
        student.setStudId(3);
        student.setName("student_"+3);
        student.setEmail("student_"+3+"@email.com");
        student.setDob(new Date());
        studentService.createStudent(student);
        Student newStudent = studentService.findStudentById(3);
        Assert.assertNotNull(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;
本文转自博客园xingoo的博客,原文链接:Mybatis入门例子,如需转载请自行联系原博主。
【云栖快讯】一站式开发者服务,海量学习资源免费学  详情请点击

网友评论