1.Dao
package com.leo.dao;
import com.leo.pojo.User;
import java.util.List;
public interface UserDao {
// 查询全部用户
List<User> getUserList();
// 根据id查询用户
User getUserById(int id);
// 增加用户
int addUser(User user);
// 修改用户
int updateUser(User user);
// 删除用户
int deleteUser(int id);
}
2.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">
<mapper namespace="com.leo.dao.UserDao">
<select id="getUserList" resultType="com.leo.pojo.User">
select * from mybatis.user;
</select>
<select id="getUserById" resultType="com.leo.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id};
</select>
<insert id="addUser" parameterType="com.leo.pojo.User">
insert into mybatis.user(id, name, pwd) values(#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.leo.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>
3.测试代码
package com.leo.dao;
import com.leo.pojo.User;
import com.leo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
// 获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭sqlSession
sqlSession.close();
}
}
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int res = mapper.addUser(new User(4, "zhaoliu", "1688888"));
if (res > 0) {
System.out.println("插入成功");
}
// 提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int res = mapper.updateUser(new User(4, "zhaoliu123", "123"));
if (res > 0) {
System.out.println("更新成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int i = mapper.deleteUser(4);
if (i > 0) {
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
}
4.执行