sourcecode

My Batis, 인서트의 자동 생성 키를 얻는 방법은?[MySql]

copyscript 2023. 10. 11. 20:53
반응형

My Batis, 인서트의 자동 생성 키를 얻는 방법은?[MySql]

MyBatis로 삽입 키를 생성하려면 어떻게 해야 합니까?이 질문에 대해 여러 페이지를 읽었지만 아직 차단되어 있습니다. 누가 도와주실 수 있나요?이게 내 암호입니다.

표:

ID_ERROR long primary key
DATE timestamp
TYPE varchar
MESSAGE varchar
SOURCE varchar

다오:

Long returnedId = 0L;
MyMapper myMapper = this.sqlSession.getMapper(MyMapper.class);
myMapper.insertRecord(returnedId, Utils.now(), t.getClass().getName(), t.getMessage(), c.getName());
return returnedId;

맵퍼.자바:

public void insertRecord(@Param("returnedId") Long returnedId, @Param("timestamp")Timestamp timestamp,@Param("type") String type,@Param("message") String message,@Param("source") String source);

mapper.xml

 <insert id="insertRecord" parameterType="map" useGeneratedKeys="true"  keyProperty="ID_ERROR">
    INSERT INTO errors (
        DATE,
        TYPE,
        MESSAGE,
        SOURCE
    )
    VALUES (
        #{timestamp},
        #{type},
        #{message},
        #{source}
    )
    <selectKey resultType="long" order="AFTER" keyProperty="returnedId">
        SELECT LAST_INSERT_ID() as returnedId
    </selectKey>
</insert>

뭐가 잘못됐나요?이 인서트의 생성된 키는 어떻게 얻을 수 있습니까?감사합니다!

저에게는 이렇게 작동합니다(mybatis 3.x)..ID는 mysql 테이블에서 자동 증분으로 설정해야 합니다.

<insert id="createEmpty" parameterType="Project" useGeneratedKeys="true" keyProperty="project.projectId" keyColumn="PROJECT_ID">
    INSERT INTO PROJECT (TITLE,DESCRIPTION)
    VALUES
    (#{title},#{description})
</insert>

keyProperty="project.projectId"그리고.useGeneratedKeys="true"

인터페이스는 다음과 같습니다.

public int createEmpty(@Param("project") Project project, @Param("title") String title,
    @Param("description") String description);

pojo의 id 속성에 자동으로 할당되는 값을 가져오려면 다음을 사용합니다.

projectRepository.createEmpty(p, "one", "two");
System.err.print(p.getProjectId() + "\n");

두 가지 방법으로 이를 달성할 수 있습니다.

  1. 사용함으로써useGeneratedKeys="true", keyProperty="id", keyColumn="id"

    keyProperty과 POJO하고를 합니다.keyColumn된 열 .

  2. 사용함으로써<selectKey/>g

MyBatis 설명서를 살펴보면 GeneratedKeys를 사용하고 keyProperty는 자동 증분 데이터를 가져오는 데 필요한 것입니다(일부 데이터베이스의 경우 keyColumn을 추가해야 함).

보시다시피 getGeneretadKeys 메서드를 database의 JDBC에서 구현하는지 여부와 방법에 따라 생성된 키를 사용합니다.

예를 들어, mysql 또는 H2의 경우 getGeneretadKeys는 하나의 열만 지원합니다.마지막으로 생성된 키는 getGeneretadKeys에 의해 반환되는 키가 됩니다.

결론적으로, 사용자의 경우 UseGeneratedKeys 및 keyProperty(ID_ERROR auto_increment)만 추가하면 됩니다.

mapper.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>

인터페이스.java

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

생성된 키를 검색하는 데 여전히 문제가 있는 경우 mysql의 JDBC 설명서도 확인하십시오(이전 버전에서는 getGeneretadKeys를 구현하지 않을 수 있음).

쉬운 솔루션:

사용하다KeyPropertys로 여기다objectName.AutoincrementId아래와 같이...

useGeneratedKeys="true", KeyProperty="person.id", KeyColumn="id"

xml 파일에서 5줄 아래로 놓기:

<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>

Java 메인 클래스에서 이 메서드를 만들고 메인 메서드에서 호출합니다.

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

하지만 PetDVO 클래스는 직접 만들어야 합니다.여기까지입니다.

Mapper 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>

자바 사이드

@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;
}

sql을 삽입하고 RETURN 표시를 사용하여 주석 선택을 사용합니다.

다음 코드는 Postgres, MyBatis 3.5.0에 적합합니다.

    @Select("insert into db_mutil_route(user_id, pk, instance_id, name, create_time, update_time) values(#{userId}, #{pk}, #{instanceId}, #{name}, now(), now()) RETURNING id")
    @Options(flushCache = Options.FlushCachePolicy.TRUE, useGeneratedKeys = true, keyProperty = "id", keyColumn="id")
    Route insert(Route dbRoute);

참조 : https://github.com/mybatis/mybatis-3/issues/1293

다음 단계를 수행하십시오.

  1. ID를 특성으로 하는 오류 POJO 생성

  2. returnId를 아래와 같이 오류로 바꿉니다.

public void insertRecord(@Param("error")) 오류 오류, @Param("timestamp")타임스탬프 타임스탬프, @Param("type") 문자열 유형, @Param("message") 문자열 메시지, @Param("source") 문자열 소스);

  1. keyProperty="를 변경합니다.ID_ERROR"을(를) keyProperty="error.id "에 연결합니다.

  2. 제거한다.

    <selectKey resultType="long" order="AFTER" keyProperty="returnedId">
        SELECT LAST_INSERT_ID() as returnedId
    </selectKey>
    

삽입됩니다.id인에error.id

생성된 기본 키를 가져오려면 인수를 다음과 같이 전달해야 합니다.Map아니면POJO Object

public void insertRecord(Map<String, Object> map);

매핑 방법을 호출할 때 값을 매핑에 넣습니다.

Map<String, Object> map = new HashMap<String, Object>();
map.put("returnedId", 0);
map.put("message", message);
// other paramters
mapper.insertRecord(map);
return map.get("returnedId");

언급URL : https://stackoverflow.com/questions/18507508/mybatis-how-to-get-the-auto-generated-key-of-an-insert-mysql

반응형