Mapper代理开发原因
- 程序员只需要编写mapper接口和mapper.xml映射文件,Mybatis可以自动生成mapper接口实现类代理对象。
- 只不过程序员在编写mapper接口时 需要遵循一些开发规范:
1.mapper.java接口名跟mapper.xml映射文件相同并且在同一个包下 2 . 在mapper.xml映射文件中,namespace="mapper接口地址" --完全包名.mapper接口名 3 . mapper.java接口中的方法名和mapper.xml中statement的id值一致 3. mapper.java接口中的方法输入参数类型和mapper.xml中statement和parameterType指定的类型一致 4. mapper.java接口中的方法返回值类型和mapper.xml中statement的resultType指定的类型一致 5. SqlMapconfig.xml配置文件中--由于使用mapper代理方式,改为加载mapper接口。
传统方式使用mabatis进行Dao开发:
编写配置文件->编写mabatis映射文件->dao接口->dao实现类(里面靠sqlfactory实现各种接口)
Mapper代理模式进行Dao层开发
SqlMapperConfig核心配置文件:
<?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"/> <typeAliases> <package name="com.msb.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="cl091900"/> </dataSource> </environment> </environments> <mappers> <mapper class="com.msb.mapper.DeptMapper"></mapper> </mappers> </configuration>
DeptMapper.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="com.msb.mapper.DeptMapper"> <!-- id要和方法名相同--> <select id="selectAll" resultType="dept"> select * from dept </select> <select id="selectOneById" resultType="dept" parameterType="int"> select * from dept where deptno=#{id} </select> <insert id="insertDept" parameterType="dept" > insert into dept(deptno,dname,loc) values (#{deptno},#{dname},#{loc}) </insert> <update id="updateDept" parameterType="dept"> update dept set dname =#{dname},loc =#{loc} where deptno=#{deptno} </update> <delete id="deleteDept" parameterType="int"> delete from dept where deptno= #{id} </delete> </mapper>
DeptMapper接口
public interface DeptMapper { //查询部门信息 List<Dept> selectAll() throws Exception; //根据主键查询单个部门信息 Dept selectOneById(int id) throws Exception; int insertDept(Dept dept) throws Exception; int updateDept(Dept dept) throws Exception; int deleteDept(int id) throws Exception; }
- 测试类:
public class Test { private SqlSessionFactory factory; @Before public void init() throws IOException{ InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); factory=builder.build(stream); } @org.junit.Test public void test() throws Exception { DeptMapper deptMapper=factory.openSession().getMapper(DeptMapper.class); System.out.println(deptMapper.selectOneById(1)); } }