简单使用
Mapper动态代理开发遵从的规范
- sql映射文件的namespace必须和mapper接口的全限定类名保持一致
- mapper接口的接口方法名必须和xml中的sql语句id保持一致
- mapper接口的接口方法形参类型必须和sql语句的输入参数类型保持一致
- mapper接口的接口方法返回类型必须和sql语句的resultType保持一致
- 定义接口(放到mapper包下,将mapper的xml放到和接口同样的路径)
public interface UserMapper { User queryUserById(Integer id); }
- 配置mapper.xml文件
<!-- namespace属性值=接口全限定名--> <mapper namespace="com.itheima.mapper.UserMapper"> <!-- id属性值=方法名--> <select id="queryUserById" parameterType="Integer" resultType="com.itheima.pojo.User"> select * from user where id=#{id} </select> </mapper>
- 使用
@Test public void userMapper() throws IOException { InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserById(2); System.out.println(user); }
全局配置文件mappers
- mappers注册sql映射文件的
- resource属性加载sql映射文件
- mapper class 单个注册
- package 批量扫描注册
<mappers>
<mapper resource="mapper/UserMapper.xml" />
<mapper class="com.itheima.mapper.UserMapper"></mapper>
<package name="com.itheima.mapper"></package>
</mappers>
使用注解简化(去掉mappper.xml)
传统xml的配置方式
public interface UserMapper {
int saveUser(User user);
List<User> queryUser();
}
<?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.itheima.mapper.UserMapper">
<insert id="saveUser" parameterType="user">
insert into user values (null,#{username},#{sex},#{birthday},#{address})
</insert>
<select id="queryUser" resultType="user">
select * from user
</select>
</mapper>
通过注解去简化可以变成
public interface UserMapper {
@Insert(" insert into user values (null,#{username},#{sex},#{birthday},#{address})")
int saveUser(User user);
@Select("select * from user")
List<User> queryUser();
}