1、我们先定义增删改查的接口操作,我们在接下来的运行中只需要考虑dao文件中的两个便可
package com.xie.dao;
import com.xie.pojo.User;
import java.util.List;
//等价于mapper 一定创建的是一个接口
public interface UseDao {
//查询全部用户
List<User> getUserList();
//根据ID查询用户信息
User getUserById(int id);
//insert 一个用户
int addUser(User user);
//修改用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
}
2、在XML文件中通过Mysql语句进行增删改查操作
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xie.dao.UseDao">
<!--标签和Sql语句返回值-->
<select id="getUserList" resultType="com.xie.pojo.User">
select * from mybatis.user1
</select>
<!--parameterType 需要输入的参数类型 #取数据操作和参数名字一样-->
<select id="getUserById" resultType="com.xie.pojo.User" parameterType="int">
select * from mybatis.user1 where id = #{id}
</select>
<!--insert一个用户然后插入 权限命名 全称-->
<!--对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.xie.pojo.User">
insert into mybatis.user1 (id, name, pwd) values(#{id},#{name},#{pwd});
</insert>
<!--修改用户-->
<update id="updateUser" parameterType="com.xie.pojo.User">
update mybatis.user1 set name = #{name}, pwd=#{pwd} where id = #{id}
</update>
<!--删除一个用户-->
<delete id="deleteUser" parameterType="int">
delete from mybatis.user1 where id = #{id}
</delete>
</mapper>
3、编写测试类编程 一定在增删改查后进行提交事务操作
package com.xie.dao;
import com.xie.pojo.User;
import com.xie.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UseDaoTest {
@Test
public void test(){
//第一步获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一 执行sql 通过接口的Class对象获得相应的接口
UseDao userDao = sqlSession.getMapper(UseDao.class);
//快速生成对象 ctrl+alt+v
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UseDao mapper = sqlSession.getMapper(UseDao.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
//提交事务
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UseDao mapper = sqlSession.getMapper(UseDao.class);
User user = new User(7,"chenqq","152364");
int id = mapper.addUser(user);
System.out.println(id);
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UseDao mapper = sqlSession.getMapper(UseDao.class);
User user = new User(2,"qqchen","165985");
int id = mapper.updateUser(user);
System.out.println(id);
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UseDao mapper = sqlSession.getMapper(UseDao.class);
int id = mapper.deleteUser(7);
System.out.println(id);
//提交事务
sqlSession.commit();
sqlSession.close();
}
}