1.每一个Dao接口对应一个xml文件
- 最好名字要一致,方便管理
//Dao接口
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据id查询用户
User getUserById(int id);
//添加用户
int insertUser(User user);
//修改
int updateUser(User user);
//删除
int deleteUser(int id);
}
对应的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 是要绑定的类的路径-->
<mapper namespace="org.example.dao.UserMapper">
<!--进行查询操作 id是对应类的方法名 resultType是返回的结果集-->
<select id="getUserList" resultType="org.example.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="org.example.pojo.User">
select * from mybatis.user where id=#{id}
</select>
<insert id="insertUser" parameterType="org.example.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="org.example.pojo.User">
update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
</mapper>
2.xml文件编写规则
-
xml文件注意事项
<mapper namespace="org.example.dao.UserMapper"></mapper>
namespace是对应Dao文件的java路径
以id查询为例
//根据id查询用户 java代码 User getUserById(int id);
<select id="getUserById" parameterType="int" resultType="org.example.pojo.User">
select * from mybatis.user where id=#{id}
</select>
id为Dao接口中对应的方法名 parameterType是方法中参数的类型 resultType是sql语句执行狗返回的结果类型
-
sql语法
遵从基本的sql语法,
可以通过#{属性}的写法来获取参数中的值
3.测试
- 注意在删除、修改操作的时候要提交事务
- 注意要关闭事务
@Test public void getUserById(){ //获取sqlSession实例 SqlSession sqlSession= MybatisUtils.getSqlSession(); //获取Dao层类的实例 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //调用对用Dao层类的方法 User user=userMapper.getUserById(1); System.out.println(user); //关闭事务 sqlSession.close(); } @Test public void insertUser(){ SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int res= userMapper.insertUser(new User(4,"测试","000000")); if(res>0){ System.out.println("插入成功"); System.out.println("-----------------------------------"); List<User> userList= userMapper.getUserList(); for (User user : userList) { System.out.println(user); } } //提交事务 sqlSession.commit(); //关闭事务 sqlSession.close(); }