需求:根据用户id查询用户信息
1.实现原理
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
2.Mapper接口开发需要遵循以下规范:
- Mapper.xml文件中的namespace与mapper接口的类路径相同。
- Mapper接口方法名和Mapper.xml中定义的每个statement的id相同 。
- Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同。
- Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同。
3.工程结构如图所示,请自行增减相关目录和文件
开发步骤
1.mybatis.xml
<?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>
<!-- 环境配置,和spring整合后environments配置将废除-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 1.配置数据源 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false" />
<property name="username" value="root" />
<property name="password" value="admin123" />
</dataSource>
</environment>
</environments>
<!-- 2.在全局配置文件中加载sql映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
2.mapper接口
public interface UserMapper {
User findUserById(Integer id) throws Exception;
}
3.mapper.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="mapper.UserMapper">
<!-- 根据用户id查找用户 -->
<select id="findUserById" resultType="po.User" parameterType="int">
select * from user where id=#{id}
</select>
<!-- 添加用户 -->
<insert id="insertUser" parameterType="po.User">
insert into user(id,username,birthday,sex,address) values(#{id},#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 根据id删除用户 -->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
<!-- 根据id更新用户 -->
<update id="updateUser" parameterType="po.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
where id=#{id}
</update>
</mapper>
4.po类编写
public class User {
//属性名要和数据库表的字段对应
private int id;
private String username;// 用户姓名
private String sex;// 性别
private String birthday;// 生日
private String address;// 地址
//get和set方法......
}
5.测试
public class Test {
public static void main(String[] args) throws Exception {
// 1.获取mybatis配置文件的路径
String resource = "config/mybatis.xml";
// 2.得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 3.根据mybatis配置文件的信息创建会话工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findUserById(1);
System.out.println(user);
}
}
运行测试结果如下