SQL 을 자바 메소드에 매핑하여 데이터베이스와 상호작용할 수 있게 해준다 !!
데이터베이스 작업을 추상화하여 코드 내에서 간단하게 호출할 수 있는 메소드로 select 결과도 쿼리 내에 들어가는 파라미터도 자동으로 매핑해준다
mapper 인터페이스 : 자바 메소드와 sql 매핑을 정의
mapper.xml : sql 쿼리를 정의
**src>main>java>com>example>e>domain>vo>ProductVO**_
package com.example~~경로
import lombok.Builder;
import lombok.Data;
import org.springframework.stereotype.Component;
@Component
@Data
public class ProductVO{
private Long id;
private String name;
private Double price;
private String category;
private String description;
public ProductVO() {}
@Builder
public ProductVO(Long id, String name, Double price, String category, String description){
this.id = id;
this.name= name;
this.price = price;
this.category = category;
this.description = description;
}
}
**src>main>java>com>example>e>mapper>ProductMapper**_
Mapper 인터페이스 !!
이 인터페이스는 ProductVO 객체를 사용하여 데이터베이스와 상호작용하는 메서드들을 정의한다 ~...
package com.example. ..~
imporpt com.example.e_.domain.vo.ProductVO;
import org.apache.ibatis.annotaions.Mapper;
import java.util.List;
@Mapper
public interface ProductMapper{
void insert(ProductVO vo);
// ProductVo 객체를 데이터베이스에 삽입한다
List<ProductVO> findByName(String name);
//제품 이름 바탕으로 ProductVO 객체들의 리스트를 반환한다
List<ProductVO> findByConditions(string name, String category,int price);
이름 , 카테고리 , 가격 기반 ProductVO 객체들의 리스트를 반환한다
(주어진 조건들에 맞는 제품을 데이터베이스에서 검색하는거임)
src>main>resources>mapper>ProductMapper.xml
<xml version~..
<!DOCTYPE~..
<mapper namespace="com.example.e.mapper.ProductMapper">
//namespace 속성으로 mapper xml 이랑 mapper 인터페이스를 연결한다
<insert id="insert">
insert into product
values (seq_product.nextval, #{name}, #{price}, #{category}, #{description})
</insert>
</mapper>
이제 데이터베이스에 잘 insert 되는지 test ㄱㄱ
**src>test>java>com>example>e>mapper>ProductMapperTest**_
package com.example.e.mapper;
import com.example.e.domain.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.booot.test.conteext.SpringBootTest;
import java.util.List;
@SpringBootTest
@Slf4j
class ProductMapperTest{
@Autowired
private ProductMapper productMapper;
@Test
void insertTest(){
ProductVO vo =
ProductVO.builder()
.name("ipad"
.price(999.4)
.catgory("electronic")
.description("fastandgood")
.build();
productMapper.insert(vo);
}