AI딥러닝/SporingBoot

Query과 Interface를 이용하여 두 개 이상의 테이블 조인하기

Ystory96 2026. 1. 12. 11:52

 

# 문제1

Q. 주민번호 입력하고 성별 구하기

S . 주민번호 8번째 자리의 숫자에 따라 case when then 사용하기

public interface SbInterface {

    String getName();
    String getJumin();
    String getSb();
    int getAge();

}
@Query(value = """
        select name,
        case
            when substr(jumin,8,1) in('1','3') then '남자'
            when substr(jumin,8,1) in('2','4') then '여자'
        end as sb,
        to_number(to_char(sysdate,'yyyy')) -
        to_number(
            case
                when substr(jumin,8,1) in ('1','2') then '19'
                when substr(jumin,8,1) in ('3','4') then '20'
        end || substr(jumin,1,2)) as age
        from sample
        """,nativeQuery = true)
List<SbInterface> sbage();

 

 

#  문제 2

Q. 카드번호, 이름, 전화번호 입력하고(테이블1) 금액전체내역, 주소(테이블2) 출력하기

S. 두개의 테이블 join on,  group by 하기

public interface OutInterface {
    long getCard_bunho();
    String getName();
    String getTel();
    int getTotal();
    String getAddress();
}
@Query(value = """
       
       select cm.card_bunho, cm.name, cm.tel, sum(cu.price) as total, ca.address 
       from Card_member cm join Card_user cu
       on cm.card_bunho = cu.card_bunho join Card_add ca
       on ca.card_bunho = cu.card_bunho
       group by cm.card_bunho, cm.name, cm.tel, ca.address
             
       """,nativeQuery = true)

List<OutInterface> total();

 

 

#  문제 3

Q. 고객 번호와 이름 입력하고 고객이 쓴 총 비용 출력하기

S. 두개의 테이블 join on,  group by, order by 하기

public interface CardInterface {

    long getCustno();
    String getCustname();

    int getAmount();

}
@Query(value = """
    select m.custno   as custno,
           m.custname as custname,
           sum(s.price) as amount
    from member_tbl_02 m
    join money_tbl_02 s
      on s.custno = m.custno
      
    group by m.custno, m.custname
    order by m.custno
    """, nativeQuery = true)

    List<CardInterface> cardquery();
}

 

 

 

 

#  문제 4

Q. 원글을 입력하고 출력한 뒤 출력한 게시글에서 댓글달기

S. 게시글 DTO의 번호와 댓글 dTO의 번호가 일치하면 출력하도록 함

 

1. DTO

public class BoardDTO {
    long bnum;//글번호
    LocalDate bdate;
    String btitle;//글제목
    String bwriter;//글작성자
    String bcontent;//글내용
    int bcount=0;
public class BoardReply {
    long brnum;//댓글번호
    String brwriter;//댓글작성자
    String brcontent;//댓글내용
    long brnum2;//원글번호

 

2. Interface

public interface BoderReplyInterface {
    long getBrnum();//댓글번호
    long getBrnum2();//원글번호
    String getBrwriter();//댓글작성자
    String getBrcontent();//댓글내용
}

 

3. Controller

@GetMapping("/bout")
 public String kk4(Model mo){
 //List<BoardEntity>list= boardService.allout();
 List<BoardListInterface> list = boardService.alloutWithReplyCount();
 mo.addAttribute("list",list);
 return "/board/out";

 

4. Repository

@Query(value = """
    select brnum,brnum2,brwriter,brcontent 
    from boardreply where brnum2=:bnum
    
    """,nativeQuery = true)

List<BoderReplyInterface> replyout(@Param("bnum")long bnum);