MyBatis,如何获取插入的自动生成的键 [MySql]

mysql

1个回答

写回答

17761293069

2025-07-02 15:45

+ 关注

MySQL
MySQL

使用MyBatis获取插入的自动生成的键

在使用MyBatis进行数据库操作时,有时我们需要获取插入操作生成的自动生成的键值,以便后续的操作中使用。对于MySQL数据库而言,我们可以通过设置useGeneratedKeys和keyProperty来实现获取自动生成的键。

代码示例

下面是一个使用MyBatis获取插入的自动生成的键的示例代码:

Java

// 定义Mapper接口

public interface UserMapper {

// 插入用户信息并返回自动生成的主键

@Insert("INSERT INTO users (name, age) VALUES (#{name}, #{age})")

@Options(useGeneratedKeys = true, keyProperty = "id")

int insertUser(User user);

}

// 定义实体类

public class User {

private Long id;

private String name;

private Integer age;

// 省略getter和setter方法

}

// 使用Mapper接口

public class MAIn {

public static void mAIn(String[] args) {

// 创建SqlSessionFactory

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()

.build(Resources.getResourceAsStream("mybatis-config.XML"));

// 创建SqlSession

try (SqlSession sqlSession = sqlSessionFactory.openSession()) {

// 获取Mapper接口的实例

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 创建一个User对象

User user = new User();

user.setName("John");

user.setAge(25);

// 插入用户信息并返回自动生成的主键

int rows = userMapper.insertUser(user);

// 获取自动生成的主键值

Long generatedKey = user.getId();

System.out.println("插入成功,生成的主键值为:" + generatedKey);

}

}

}

在上述示例代码中,首先定义了一个UserMapper接口,其中使用@Insert注解标注了插入用户信息的SQL语句,并通过@Options注解的useGeneratedKeys属性设置为true,keyProperty属性设置为id,以告知MyBatis获取自动生成的键值。然后,在MAIn类中创建SqlSessionFactory和SqlSession,通过getMapper方法获取UserMapper接口的实例。接着,创建一个User对象,设置用户信息,并调用insertUser方法插入用户信息。最后,通过getId方法获取自动生成的主键值。

通过设置useGeneratedKeys和keyProperty属性,我们可以方便地使用MyBatis获取插入操作生成的自动生成的键值。这对于一些需要在插入操作后立即使用自动生成的键值的场景非常有用。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号