개발/DB

[Mybatis] selectKey 태그 key값 리턴

Yunikism 2024. 1. 30. 15:14
728x90

 

개발을 하다보면 가끔 insert 후 키값을 받아와야할때가 있다.

 

insert 후 생성된 키를 다른 테이블에 외래키로 넣는다던지..

 

그럴때는 

 

selectKey 태그를 이용하여 키값을 리턴받으면 된다.

 

 

    <insert id="insertTestSelectKey" parameterType="java.util.Map">
        <selectKey keyProperty="product_no" resultType="long" order="BEFORE">
			SELECT MAX(product_no) FROM tb_test WHERE product_no = #{product_no}
        </selectKey>
        INSERT INTO
        tb_test
        (
            product_nm,
            product_no,
            reg_date,
            reg_id,
            mod_date,
            mod_id
        )
        VALUES
        (
            #{product_nm},
            #{product_no},  -- selectKey태그에서 keyProperty 변수명을 파라미터로 사용가능
            now(),
            #{reg_id},
            now(),
            #{mod_id}
        );
    </insert>

 

selectKey 태그에서 지정한 keyProperty 변수명을

 

insert 문에서 파라미터처럼 사용이 가능하다.

 

 

 

selectKey 에 order은 BEFORE, AFTER로 insert 쿼리 이후에 실행할지 이전에 실행할지를 정해준다.

즉 

 

BEFORE 를 사용할 경우에는 selectKey가 insert문 이전에 실행되어 keyProperty 변수에 담겨서 파라미터처럼 사용이 가능하고 

 

AFTER 는 insert 문 이후에 실행되어 keyProperty 에 담기게된다

 

service단에서 keyProperty 에 담긴 key값을 확인하려면 파라미터로 넘겨준 Map을 확인해보면 된다.

 

@Service
public class TestService {

    @Autowired
    private TestDao testDao;
    
    public Map insertTestSelectKey(Map<String,Object> param) {
    
   		 testDao.insertTestSelectKey(param);
         
		 System.out.println("받은키값 : " + param.get("product_no"));
        
        ....
    }
    
	

}