您的位置:宽带测速网 > 编程知识 > MyBatis中怎么实现自动递增主键生成

MyBatis中怎么实现自动递增主键生成

2025-06-23 19:43来源:互联网 [ ]

在MyBatis中实现自动递增主键生成可以通过数据库的自增长字段来实现。具体步骤如下:

    在数据库表中定义一个自增长的主键字段,比如使用MySQL数据库可以使用auto_increment关键字定义主键字段。

    在对应的实体类中定义一个与数据库主键字段对应的属性,并添加对应的注解。

public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String password;// getter and setter methods}
    在MyBatis的Mapper文件中配置插入语句,使用数据库的自增长主键字段来为主键生成值。
<insert id="insertUser" parameterType="User"><selectKey keyProperty="id" resultType="java.lang.Long" order="AFTER">SELECT LAST_INSERT_ID()</selectKey>INSERT INTO user (username, password) VALUES (#{username}, #{password})</insert>

在插入数据时,MyBatis会自动为主键字段生成递增的值,并将该值赋给实体类对应的属性。