天天看點

c mysql 插入傳回id_Java MySQL使用MyBatis插入(insert)資料擷取自動生成主鍵的方法及示例代碼...

1、配置xml中insert标簽

1) xml中添加下面内容

useGeneratedKeys="true" keyProperty="id">

INSERT INTO Pet (NAME, OWNER, SPECIES, SEX, BIRTH)

VALUES (#{name}, #{owner}, #{species}, #{sex}, #{birth})

2) 擷取自動生成主鍵public int createPet(PetDVO petDVO) throws Exception {

HashMap inputMap = new HashMap();

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());

SqlSession sqlSession = getSqlSession();

sqlSession.insert("createPet", inputMap);

sqlSession.commit();

BigInteger newID = (BigInteger)inputMap.get("id");

return newID.intValue();

}

2、配置resultMap和insert标簽

1) xml中配置

INSERT INTO errors (

DATE,

TYPE,

MESSAGE,

SOURCE

)

VALUES (

#{timestamp},

#{type},

#{message},

#{source}

)

2) Interface.java代碼public void insertRecord(@Param("error") Error error);

相關文檔:

3、配置insert和selectKey标簽

1) xml中配置

useGeneratedKeys="true" keyProperty="demoId" keyColumn="DEMOID">

INSERT INTO TBL_DEMO (DEMONAME,DEMODESCRIPTION)

VALUE (#{demoName},#{demoDescription})

SELECT LAST_INSERT_ID();

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;

}