【MyBatis】MyBatis三种开发方式

三种开发方式

MyBatis三种开发方式分别为:
1. dao对象 + xml
2. mapper代理对象 + xml
3. mapper代理对象 + 注解
其中,第三种代理对象 + 注解最为常见。

dao对象 + xml

dao层对象手动创建SqlSession对象,手动实现方法,并和xml文件中的标签进行sql配对。
mybatis-config.xml

<mappers>
    <mapper resource="mapper/StudentMapper.xml"></mapper>
</mappers>

StudentSerivce.java

public class StudentService {

    private StudentDao dao = new StudentDao();

    public void insert(Student student) {
        dao.insert(student);
    }

}

StudentDao.java

public class StudentDao {

    private SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    private SqlSessionFactory factory = builder.build(Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml"));
    private SqlSession sqlSession = factory.openSession(true);
    
    public void insert(Student student) {
        sqlSession.insert("insert", student);
    }

}

StudentMapper.xml

<?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="dao.StudentDao">
    <insert id="insert">
        insert into student (`name`, `age`, `sex`) values (#{name}, #{age}, #{sex})
    </insert>
</mapper>

mapper代理对象 + xml

使用动态代理机制,dao层接口化,底层自动创建代理对象代替dao对象创建SqlSession,并且自动与xml文件进行sql配对。
注意,这里代理对象管理的SqlSession匹配方法,规定了方法的id必须为方法名。
mybatis-config.xml

<mappers>
    <mapper resource="mapper/StudentMapper.xml"></mapper>
</mappers>

StudentSerivce.java

public class StudentService {

    private StudentDao dao = SqlSessionUtil.getMapper(StudentDao.class);

    public void insert(Student student) {
        dao.insert(student);
    }

}

StudentDao.java

public interface StudentDao {

    void insert(Student student);

}

StudentMapper.xml

<?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="dao.StudentDao">
    <insert id="insert">
        insert into student (`name`, `age`, `sex`) values (#{name}, #{age}, #{sex})
    </insert>
</mapper>

mapper代理对象 + 注解

使用动态代理机制,dao层接口化,底层自动创建代理对象代替dao对象创建SqlSession,并且自动从注解中提取sql。
注意,使用注解后,就可以省去对应的一个xml文件。
mybatis-config.xml

<mappers>
    <mapper class="dao.StudentDao"></mapper>
</mappers>

StudentSerivce.java

public class StudentService {

    private StudentDao dao = SqlSessionUtil.getMapper(StudentDao.class);

    public void insert(Student student) {
        dao.insert(student);
    }

}

StudentDao.java

public interface StudentDao {

    @Insert("insert into student (`name`, `age`, `sex`) values (#{name}, #{age}, #{sex})")
    void insert(Student student);

}

你可能感兴趣的:(【MyBatis】MyBatis三种开发方式)