Java MySQL使用MyBatis插入(insert)数据获取自动生成主键的方法及示例代码

本文主要介绍Java中,使用MyBatis进行数据库数据插入,获取自动生成的主键(自增主键)的三种配置方法,及相关示例代码。

1、配置xml中insert标签

1) xml中添加下面内容

<insert id="createPet" parameterType="java.util.Map"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO Pet (NAME, OWNER, SPECIES, SEX, BIRTH)
VALUES (#{name}, #{owner}, #{species}, #{sex}, #{birth})
</insert>

2) 获取自动生成主键

public int createPet(PetDVO petDVO) throws Exception {
HashMap<String, Object> inputMap = new HashMap<String, Object>();
inputMap.put("name", petDVO.getName());
inputMap.put("owner", petDVO.getOwner());
inputMap.put("species", petDVO.getSpecies());
inputMap.put("sex", petDVO.getSex());
inputMap.put("birth", petDVO.getBirth());
/**
* Get the sql session and commit the data
*/
SqlSession sqlSession = getSqlSession();
sqlSession.insert("createPet", inputMap);
sqlSession.commit();
BigInteger newID = (BigInteger)inputMap.get("id");
return newID.intValue();
}

2、配置resultMap和insert标签

1) xml中配置

<resultMap type='pathToJavaClass/Error' id='error'>
<id property='id' column='ID_ERROR' />
<result property='timestamp' column='DATE' />
<result property='type' column='TYPE'/>
<result property='message' column='MESSAGE'/>
<result property='source' column='SOURCE'/>
</resultMap>
<insert id="insertRecord" parameterType="error" useGeneratedKeys="true" keyProperty="id">
INSERT INTO errors (
DATE,
TYPE,
MESSAGE,
SOURCE
)
VALUES (
#{timestamp},
#{type},
#{message},
#{source}
)
</insert>

2) Interface.java代码

public void insertRecord(@Param("error") Error error);

相关文档:

MyBatis documentation

mysql

3、配置insert和selectKey标签

1) xml中配置

<insert id="saveDemo" parameterType="com.abc.demo"
useGeneratedKeys="true" keyProperty="demoId" keyColumn="DEMOID">
INSERT INTO TBL_DEMO (DEMONAME,DEMODESCRIPTION)
VALUE (#{demoName},#{demoDescription})
<selectKey keyProperty="demoId" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID();
</selectKey>
</insert>

2) 使用代码

@Override
public boolean saveDemo(Demo demo) {
boolean status = false;
SqlSession session = this.sqlSessionFactory.openSession();
try {
DemoMapper mapper = session.getMapper(DemoMapper.class);
mapper.saveDemo(demo);
session.commit();
status = true;
} catch(PersistenceException e) {
System.out.println(e);
} finally {
session.close();
}
return status;
}


推荐阅读
cjavapy编程之路首页