mybatis mapper (service X, xml X)

이태규·2022년 3월 31일
0

spring

목록 보기
34/64

1. mapper 파일 만들고 application에 연결하기

@ComponentScan(basePackages = { "com.example.controller", 
"com.example.service", "com.example.config" })
@MapperScan(basePackages = "com.example.mapper")
public class Boot20220328Application {

	public static void main(String[] args) {
		SpringApplication.run(Boot20220328Application.class, args);
	}

}
  • 컨트롤러, 환경파일, 서비스(mybatis xml버전)
@ComponentScan(basePackages = { "com.example.controller", 
"com.example.service", "com.example.config" })
  • Mapper(mybatis 2버젼(서비스 없는 버젼))
@MapperScan(basePackages = "com.example.mapper")

config 에 있던 파일에서

Resource[] arrResource = new PathMatchingResourcePatternResolver()
                .getResources("classpath:/mappers/*Mapper.xml");
        sqlSessionFactoryBean.setMapperLocations(arrResource);
        return sqlSessionFactoryBean.getObject();

위의 부분은 xml파일을 통해 mybatis를 사용하는 방법이다. 옛날 방법
service와 xml을 사용하지 않는 방법에서는 위와 같은 설정은 필요없음.

코드

package com.example.mapper;

import com.example.dto.MemberDTO;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface MemberMapper {

        // 파라미터 n개 가능 대신 명칭을 부여해줘야 함.
        // INSERT INTO 테이블 명 (컬럼명들) VALUES(추가할 값들)
        @Insert({
                        "INSERT INTO MEMBER(UEMAIL, UPW, UNAME, UPHONE, UROLE", 
                        ",UREGDATE)VALUES(#{obj.uemail},#{obj.upw},#{obj.uname},",
                        "#{obj.uphone},#{obj.urole}, CURRENT_DATE" })
        // 길면 ,찍고 하면됨 ,가 +임 VALUES앞에 띄웠음
        public int memberJoin(@Param(value = "obj") MemberDTO member);
        // 멤버에 담긴걸 OBJ를 써서 하겠다라는 뜻 파라미터가 여러개이면 안되니까

        @Select({
                        "SELECT UEMAIL, UNAME, UROLE FROM MEMBER",
                        " WHERE UEMAIL=#{email} AND UPW=#{pw}"
        })
        public MemberDTO memberLogin(
                        @Param(value = "email") String em,
                        @Param(value = "pw") String pw);
        // em에 담고 email을 쓰는거임 em 대신 아무거나 써도됨
}

위에 어노테이션을 붙여준다.
interface를 통해 파일을 만들어줌
위에 어노테이션으로 CRUD방법을 정한다. 안에 쿼리문 작성
길어서 띄워줄 때에는 + 대신 ,를 쓴다.

profile
한 걸음씩 나아가자

0개의 댓글