Mybatis学习3——动态代理

动态代理只需要接口和mapper映射文件不需要实现类

动态代理规范

1、namespace必须是接口的全路径
2、接口的方法必须与sql的id一致
3、接口的入参与parameterType类型一致
4、接口的返回值必须与resultType类型一致

1、写接口UserMapper.java

package mapper;

import java.util.List;

import pojo.User;

public interface UserMapper {
User getUserBYId(Integer id);
List<User> getUSerByUserName(String userName);
}

2、mapper映射文件UserMapper.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">
<!-- namespace命名空间,隔离sql文件 -->
<!-- #{}占位符相当于jdbc的? -->
<!-- ${value} 字符串拼接 -->
<!-- 动态代理开发原则
1、namespace必须是接口的全路径
2、接口的方法必须与sql的id一致
3、接口的入参与parameterType类型一致
4、接口的返回值必须与resultType类型一致
-->
<mapper namespace="mapper.UserMapper">
<select id="getUserBYId" parameterType="int" resultType="pojo.User">
select id, username,birthday,sex,address from user where id = #{id}
</select>
<select id="getUSerByUserName" parameterType="String" resultType="pojo.User">
select id, username,birthday,sex,address from user where username like '%${value}%'
</select>
</mapper>

3、在sqlMapperConfig.xml引入mapper文件

    <mappers>
<mapper resource="mybatis/user.xml"/>
<mapper resource="mybatis/UserMapper.xml"/>
</mappers>

4、测试

package mapper;

import static org.junit.Assert.*;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import pojo.User;
import util.SqlSessionFactoryUtil; public class UserMapperTest { @Test
public void test() {
SqlSession openSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
//获得接口实现类
UserMapper mapper = openSession.getMapper(UserMapper.class);
User userBYId = mapper.getUserBYId(10);
System.out.println(userBYId);
openSession.close();
} }
上一篇:MyBatis通过Mapper动态代理来实现curd操作


下一篇:java框架之MyBatis(1)-入门&动态代理开发