Mybatis实现增删改查
作者:互联网
Mybatis实现增删改查
概述
本文主要讲述利用 Mybatis实现增删改查,详细的环境等配置详见https://www.cnblogs.com/Oh-mydream/p/16468030.html
文本仅修改核心内容,对工具类等不再做详细的展开
注意点
数据库的增删改操作需要提交事务
实践
UserDao.java
package com.kuang.dao;
import java.util.List;
import com.kuang.pojo.User;
/**
* 功能描述
*
* @since 2022-07-11
*/
public interface UserDao {
List<User> getUserList();
int addUser(User user);
int updateUser(User user);
User getUser(int id);
int deleteUser(int id);
}
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.kuang.dao.UserDao">
<select id="getUserList" resultType="com.kuang.pojo.User">
select *
from user
</select>
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into user (`id`, `name`, `pwd`)
values (#{id}, #{name}, #{pwd})
</insert>
<select id="getUser" parameterType="int" resultType="com.kuang.pojo.User">
select *
from user
where id = #{id}
</select>
<delete id="deleteUser" parameterType="int">
delete
from user
where id = #{id}
</delete>
<update id="updateUser" parameterType="com.kuang.pojo.User">
update user
set name =#{name},
pwd=#{pwd}
where id = #{id}
</update>
</mapper>
测试类
package com.kuang.dao;
import java.util.Iterator;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.kuang.pojo.User;
import com.kuang.util.MyBatisUtils;
/**
* 功能描述
*
* @since 2022-07-11
*/
public class UserDaoTest {
@Test
public void test1() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
Iterator<User> iterator = userList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
@Test
public void get() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUser(1);
System.out.println(user);
}
@Test
public void add() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int result = mapper.addUser(new User(4, "lili", "123"));
// 增删改操作需要提交事务 否则不生效
sqlSession.commit();
}
@Test
public void update() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int result = mapper.updateUser(new User(4, "lil2", "333"));
sqlSession.commit();
}
@Test
public void delete() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int result = mapper.deleteUser(4);
sqlSession.commit();
}
}
标签:mapper,UserDao,改查,增删,sqlSession,user,Mybatis,import,id 来源: https://www.cnblogs.com/Oh-mydream/p/16471750.html