MyBatis支持以下几种主键生成策略:
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (name) VALUES (#{name})
</insert>
<insert id="insertUser" parameterType="User">
INSERT INTO user (id, name) VALUES (#{id}, #{name})
</insert>
public class CustomKeyGenerator implements KeyGenerator {
@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// 生成主键的逻辑
}
@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// 处理生成的主键值
}
}
<insert id="insertUser" keyProperty="id">
<selectKey keyProperty="id" resultType="Long" order="BEFORE">
SELECT NEXTVAL('user_seq') AS id
</selectKey>
INSERT INTO user (id, name) VALUES (#{id}, #{name})
</insert>
<insert id="insertUser" parameterType="User">
<selectKey keyProperty="id" resultType="Long" order="BEFORE">
SELECT user_seq.nextval AS id FROM dual
</selectKey>
INSERT INTO user (id, name) VALUES (#{id}, #{name})
</insert>
以上是MyBatis插入数据时的几种主键生成策略,开发者可以根据具体需求选择合适的主键生成方式。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。