【Mybatis】实现修改、删除和查询功能
1.修改和删除
(1)UserMapper接口中添加方法
public interface UserMapper {
int insertUser(User user);
int updateUser(int id,User user);
int deleteUser(int id);
}
(2)映射文件SQL语句
<insert id="insertUser" parameterType="com.pxk.pojo.User">
insert into user(id, name, pwd)
values (#{id}, #{name}, #{pwd});
</insert>
<update id="updateUser" parameterType="Integer">
update user set name="熊初墨" where id=#{id};
</update>
<delete id="deleteUser" parameterType="Integer">
delete from user where id = #{id};
</delete>
(3)测试
@Test
public void test3() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int updateLine = mapper.updateUser(99);
int deleteLine = mapper.deleteUser(99);
}
2.查询
2.1 根据id查询用户信息
(1)Mapper接口方法
User getUserById(Integer id);
(2)映射文件
parameterType:参数类型
resultType:查询结果集类型
- resultTye:自动映射,用于属性名和表中字段名一致的情况
- resultMap:自定义映射,用于一对多、多对一或字段名和属性名不一致的情况
<select id="getUserById" parameterType="Integer" resultType="com.pxk.pojo.User">
select * from user where id = #{id}
</select>
(3)测试
User user = mapper.getUserById(100);
System.out.println(user);
2.2 查询所有用户信息
(1)Mapper接口方法
List<User> getAllUser();
(2)映射文件
<select id="getAllUser" resultType="com.pxk.pojo.User">
select * from user;
</select>
(3)测试
List<User> users = mapper.getAllUser();
users.forEach(user -> System.out.println(user));