MyBatis的增删改查(查询分为查询一个实体类对象、查询List集合和查询多条数据为map集合,自定义增删改查的具体内容)。用JavaEE实现
时间: 2024-02-21 08:58:14 浏览: 72
MyBatis是一种持久化框架,它可以与JavaEE中的其他框架(如Spring)一起使用。下面是一些示例代码,演示如何使用MyBatis进行增删改查。
1. 查询一个实体类对象
```
public class User {
private int id;
private String name;
private int age;
// 省略getter和setter
}
public interface UserMapper {
User selectById(int id);
}
// MyBatis XML配置文件
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" parameterType="int" resultType="com.example.model.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
// 使用MyBatis进行查询
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectById(1);
```
2. 查询List集合
```
public interface UserMapper {
List<User> selectAll();
}
// MyBatis XML配置文件
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectAll" resultType="com.example.model.User">
SELECT * FROM user
</select>
</mapper>
// 使用MyBatis进行查询
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.selectAll();
```
3. 查询多条数据为map集合
```
public interface UserMapper {
List<Map<String, Object>> selectAllAsMap();
}
// MyBatis XML配置文件
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectAllAsMap" resultType="java.util.Map">
SELECT id, name, age FROM user
</select>
</mapper>
// 使用MyBatis进行查询
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<Map<String, Object>> userList = userMapper.selectAllAsMap();
```
4. 自定义增删改查的具体内容
```
public interface UserMapper {
int insert(User user);
int update(User user);
int delete(int id);
}
// MyBatis XML配置文件
<mapper namespace="com.example.mapper.UserMapper">
<insert id="insert" parameterType="com.example.model.User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="update" parameterType="com.example.model.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
// 使用MyBatis进行增删改查
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 插入新用户
User newUser = new User();
newUser.setName("Tom");
newUser.setAge(20);
userMapper.insert(newUser);
// 更新用户信息
User updateUser = userMapper.selectById(1);
updateUser.setAge(25);
userMapper.update(updateUser);
// 删除用户
userMapper.delete(1);
```
阅读全文