mapper.XML useGeneratedKeys
时间: 2024-08-28 17:03:15 浏览: 45
`mapper.XML` 中的 `useGeneratedKeys` 是 MyBatis 框架中设置自动编号(主键自增)的一个配置属性。当你在 SQL 映射文件中插入数据,并且指定某个字段作为主键,如果设置了 `useGeneratedKeys="true"`,MyBatis 就会告诉数据库在插入操作完成后返回新生成的主键值,而不是由应用程序生成。
这个属性的作用在于,如果你的数据表支持自动递增的主键,比如一些关系型数据库中的 IDENTITY 或者 AUTO_INCREMENT,你可以通过这种方式让 MyBatis 自动获取并填充到 Java 对象中,无需手动处理。
例如:
```xml
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO users (name, email) VALUES (${name}, ${email})
<if test="id == null">
.generatedKey property="id"/>
</if>
</insert>
```
在这里,如果 `id` 参数为 `null`,MyBatis 会在插入成功后将返回的数据库自动生成的主键赋给 `User` 对象的 `id` 属性。
相关问题
帮我写一个用mybatis 完成批量扣减商品数量 的代码 包括mapper 和 mapper.xml
当你想用MyBatis完成批量扣减商品数量的操作,你需要创建一个Mapper接口、一个对应的XML映射文件以及一个Service层来调用这个Mapper。下面是一个简单的示例:
首先,创建Mapper接口(ItemMapper.java):
```java
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
public interface ItemMapper {
@Insert({
"BEGIN",
"UPDATE item SET stock = stock - #{quantity} WHERE id IN ",
"(SELECT item_id FROM order_items WHERE order_id = #{orderId})",
"AND stock > 0",
"COMMIT"
})
@Options(useGeneratedKeys = true, keyProperty = "itemId")
int deductStock(@Param("orderId") Long orderId, @Param("quantity") Integer quantity);
@Delete("DELETE FROM item WHERE id = #{itemId}")
void deleteItemById(Long itemId);
}
```
接着,创建Mapper XML配置文件(itemMapper.xml):
```xml
<?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 namespace="com.yourpackage.ItemMapper">
<insert id="deductStock" parameterType="map">
<!-- SQL 更新语句 -->
<selectKey resultType="long" order="BEFORE" keyProperty="itemId">
SELECT LAST_INSERT_ID() AS itemId
</selectKey>
${script}
</insert>
<delete id="deleteItemById" parameterType="long">
DELETE FROM item WHERE id = #{itemId}
</delete>
</mapper>
```
注意:这里的`${script}`标签需要替换为之前在Java接口中的那行SQL,即`BEGIN...COMMIT`部分。
最后,在Service层或其他业务处理地方调用Mapper方法:
```java
@Service
public class ProductService {
private final ItemMapper itemMapper;
public ProductService(ItemMapper itemMapper) {
this.itemMapper = itemMapper;
}
public void deductStockForOrder(Long orderId, Integer quantity) {
int affectedRows = itemMapper.deductStock(orderId, quantity);
// 验证影响行数是否为预期,如果有事务管理,也可以在此检查事务状态
if (affectedRows <= 0) {
// 处理异常逻辑
}
}
}
```
springmyboot+batis的代码写一个,带有依赖,yml配置,mapper.xml,entity,mapper,service,controller,application
这里是一个示例的Spring Boot + MyBatis项目的代码,包括了依赖、YAML配置文件、Mapper.xml文件、实体类、Mapper接口、Service层、Controller层和应用程序入口。
pom.xml:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
```
application.yml:
```yaml
spring:
datasource:
username: root
password: password
url: jdbc:mysql://localhost:3306/mydatabase
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
```
User.java:
```java
public class User {
private Long id;
private String name;
private Integer age;
// getter and setter methods
}
```
UserMapper.java:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(Long id);
@Insert("INSERT INTO users(name, age) VALUES(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertUser(User user);
}
```
UserService.java:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
public void insertUser(User user) {
userMapper.insertUser(user);
}
}
```
UserController.java:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("/")
public void insertUser(@RequestBody User user) {
userService.insertUser(user);
}
}
```
Application.java:
```java
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
users.xml:
```xml
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getUserById" parameterType="java.lang.Long" resultType="com.example.demo.entity.User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.demo.entity.User">
INSERT INTO users(name, age) VALUES(#{name}, #{age})
</insert>
</mapper>
```
阅读全文