mybatis 主键回西显
时间: 2025-05-29 11:38:29 浏览: 4
### MyBatis 主键回显的配置与使用
#### 使用 `useGeneratedKeys` 实现主键回显
当数据库支持自动增长字段(如 MySQL 的 AUTO_INCREMENT),可以通过设置 `<insert>` 标签中的 `useGeneratedKeys="true"` 来实现主键回显。此方式适用于大多数简单场景。
以下是具体配置示例:
```xml
<insert id="insertUser" useGeneratedKeys="true" keyProperty="userId" keyColumn="USER_ID">
INSERT INTO user (name) VALUES (#{name})
</insert>
```
- **`useGeneratedKeys=true`**: 启用数据库自动生成主键并将其回填到 Java 对象中[^2]。
- **`keyProperty="userId"`**: 指定 Java 对象中接收主键值的属性名称。
- **`keyColumn="USER_ID"`**: 映射数据库表中生成主键的列名,通常用于属性名和列名不一致的情况。
---
#### 自定义主键生成策略
对于复杂的主键生成逻辑(例如手动计算主键值或基于特定算法生成主键),可以使用 `<selectKey>` 标签来实现。
以下是一个通过 SQL 查询动态生成主键的例子:
```xml
<insert id="save" keyProperty="id" parameterType="student">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
SELECT IF(MAX(id) IS NULL, 1, MAX(id) + 2) FROM student;
</selectKey>
INSERT INTO student (id, studentName, phone, birth)
VALUES (#{id}, #{studentName}, #{phone}, #{birth});
</insert>
```
- **`order="BEFORE"`**: 表示在执行插入语句之前先获取主键值[^3]。
- **SQL 查询部分**: 动态计算主键值,确保其唯一性和连续性。
---
#### 测试代码验证主键回显功能
为了测试主键回显的功能是否正常工作,可以在单元测试中打印生成的主键值。
以下是完整的测试代码示例:
```java
@Test
public void testInsert() throws IOException {
// 加载核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建 SqlSessionFactory 工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 获取 sqlSession 对象
try (SqlSession sqlSession = factory.openSession()) {
// 获取 Mapper 接口实例
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 构造待插入的学生对象
Student student = new Student();
student.setStudentName("小白");
student.setPhone("12321");
student.setBirth(99);
// 执行插入操作
int num = studentMapper.insert(student);
// 输出生成的主键值
System.out.println("生成的主键值:" + student.getId());
// 提交事务
sqlSession.commit();
}
}
```
在此示例中,`System.out.println(student.getId());` 将会输出由数据库生成的主键值[^4]。
---
### 总结
MyBatis 支持两种主要的主键回显方式:
1. 利用数据库自带的自增机制并通过 `useGeneratedKeys` 完成主键回显。
2. 使用 `<selectKey>` 进行更灵活的手动主键生成。
每种方式都有其适用场景,开发者应根据实际需求选择合适的方案。
---
阅读全文
相关推荐


















