Mybatis insert 작업은 증가된 주 키 id를 반환합니다.

2145 단어 SSM
때때로 우리가 데이터를 삽입할 때, id는 자동으로 생성될 가능성이 높기 때문에, 만약 우리가 방금 삽입한 id를 되돌려 주려고 한다면 어떻게 합니까?
mysql 데이터에 insert 아래에 되돌아오는 형식과 값을 지정하기 위해 selectKey를 추가할 수 있습니다.
방법1:

    
     
        SELECT LAST_INSERT_ID() AS ID   
    
    insert into tb_content_category (id, parent_id, name, 
      status, sort_order, is_parent, 
      created, updated)
    values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, 
      #{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT}, 
      #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
  

여기서 resultType은 반환 유형을 나타냅니다.ID는 방금 삽입한 ID를 반환합니다.
 
방법2:
mysql 데이터에 insert에서useGeneratedKeys="true"keyProperty="id"를 추가할 수 있습니다

    
    insert into tb_content_category (id, parent_id, name, 
      status, sort_order, is_parent, 
      created, updated)
    values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, 
      #{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT}, 
      #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
  

java 코드 가져오기 id
TbContentCategory record = new TbContentCategory();
		record.setParentId(parentId);
		record.setName(name);
		Date date = new Date();
		record.setCreated(date);
		record.setUpdated(date);
		record.setStatus(1);
		record.setSortOrder(1);
		record.setIsParent(false);

		TbContentCategoryMapper.insert(record);
		
		//insert   ,id    record  ,        
		Long id = record.getId();

좋은 웹페이지 즐겨찾기