mybatis增删改查实例
时间: 2024-09-28 08:15:13 浏览: 36
MyBatis是一个优秀的持久层框架,它支持SQL映射文件来操作数据库。下面是一个简单的MyBatis增删改查的例子:
**1. 增加数据(Insert)**:
```xml
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
```
在Java代码里:
```java
User newUser = new User();
newUser.setName("张三");
newUser.setAge(20);
sqlSession.insert("insertUser", newUser);
```
**2. 删除数据(Delete)**:
```xml
<select id="deleteUserById" parameterType="int" resultType="void">
DELETE FROM user WHERE id = #{id}
</select>
```
```java
User userToDelete = new User();
userToDelete.setId(1);
sqlSession.delete("deleteUserById", userToDelete.getId());
```
**3. 更新数据(Update)**:
```xml
<update id="updateUser" parameterType="com.example.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
```
```java
User updateUser = ...; // 获取要更新的数据对象
sqlSession.update("updateUser", updateUser);
```
**4. 查询数据(Select)**:
```xml
<select id="selectUsers" resultType="com.example.User">
SELECT * FROM user WHERE age > #{minAge}
</select>
```
```java
List<User> users = sqlSession.selectList("selectUsers", Map.of("minAge", 18));
```
阅读全文