문서
https://www.w3schools.com/sql/func_mysql_last_insert_id.asp
MySQL LAST_INSERT_ID() Function
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
정의 및 사용법
LAST_INSERT_ID() 함수는 테이블에 삽입되거나 업데이트된 마지막 행의 AUTO_INCREMENT ID를 반환합니다.
통사론
LAST_INSERT_ID(expression)
매개변수 값
ParameterDescription
expression | Optional. An expressio |
예제
mybatis 에서의 사용했을때
<insert id="save">
insert into product (prod_writer_no , prod_title ,
prod_start_time ,
....;
INSERT INTO views (prod_no, prod_views)
VALUES (LAST_INSERT_ID(), 0);
</insert>
JPA 에서의 예제
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Autowired
private ProductViewsRepository productViewsRepository;
@Transactional
public void insertProduct(Product product) {
// Product 테이블에 데이터 삽입
productRepository.save(product);
// 마지막으로 삽입된 prodNo 가져오기
Long lastInsertedProdNo = productRepository.getLastInsertedProdNo();
// ProductViews 테이블에 데이터 삽입
ProductViews productViews = new ProductViews();
productViews.setProdNo(lastInsertedProdNo);
productViews.setProdViews(0); // 초기값 설정 등
productViewsRepository.save(productViews);
}
}
'데이터베이스 > MySQL' 카테고리의 다른 글
MySQL - 명령어 (0) | 2023.12.16 |
---|---|
MySQL - 시퀀스를 간단히 만들어 보자 AUTO_INCREMENT 또는 procedure 와 function (0) | 2023.12.13 |