一、mybatis实现增删改查
public interface UserMapper {
/**
* 添加用户
* @return
*/
int insertUser();
/**
* 修改用户
*/
void updateUser();
/**
* 删除用户
*/
void deleteUser();
/**
* 查询用户
* @return
*/
User selectUser();
/**
* 批量查询用户
* @return
*/
List<User> selectUserList();
}
对应的映射文件
<?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的UserMapper相对应-->
<mapper namespace="com.cjc.mybatis.mapper.UserMapper">
<!--这里的id要与mapper接口中方法名相同-->
<!--添加用户-->
<insert id="insertUser">
insert into t_user values(null ,'admin','123456',18,'男','678899@qq.com')
</insert>
<!--修改用户-->
<update id="updateUser">
update t_user set username = '小' where id = 1
</update>
<!--删除用户-->
<delete id="deleteUser">
delete from t_user where id = 1
</delete>
<!--resultType:设置默认的映射关系
resultMap:设置自定义的映射关系
-->
<!--查询用户-->
<select id="selectUser" resultType="com.cjc.mybatis.entity.User">
select * from t_user where id = 2
</select>
<select id="selectUserList" resultType="com.cjc.mybatis.entity.User">
select * from t_user
</select>
</mapper>
@Test
public void test03() throws IOException {
//加载mybatis的核心配置文件,以字节输入流方式
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory
SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
//获取SqlSession
SqlSession sqlSession = build.openSession(true);
//获取mapper接口对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//通过mapper调用updateUser()方法
mapper.updateUser();
//调用删除方法
mapper.deleteUser();
//调用查询方法
User user = mapper.selectUser();
System.out.println("user = " + user);
List<User> users = mapper.selectUserList();
users.forEach(user1 -> {
System.out.println("user1 = " + user1);
} );
}