반응형

1. dependencies

jpa 의존성과 postgreSQL 의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.postgresql:postgresql'

 

2. application.yml

spring:
##JPA 설정정보
  jpa:
    hibernate:  
      ddl-auto: update  	##update로 해놔야 테이블 update가 됨
      format_sql: true      
      naming:				
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
	##entity를 camelCase로 작성시 db에는 snake_case로 컬럼명이 들어가게 되는데 이걸 막기위함.

##POSTGRESQL 연결정보
  datasource:
    maximum-pool-size: 4
    url: jdbc:postgresql://${HOST}:5432/mydatabase
    username: ${USERNAME}
    password: ${PASSWORD}
    driver-class-name: org.postgresql.Driver

 

 

3. entity 작성

@Entity 어노테이션이 필요하다.

@Table 어노테이션으로 맵핑할 db의 테이블 이름을 적어준다. 

import org.springframework.stereotype.Component;

import javax.persistence.*;
import java.util.Date;

@Component
@Table(name = "member")  //맵핑할 db의 table 이름
@Entity(name = "member")
public class Member {

    @Id //기본 키 매핑
    @GeneratedValue(strategy = GenerationType.AUTO) //자동증가
    private long idx;
    private Date regDate;
    private String age;
    
    public long getIdx() {
        return idx;
    }
    public void setIdx(long idx) {
        this.idx = idx;
    }
    public Date getRegDate(){
        return regDate;
    }
    public void setRegDate(Date regDate){
        this.regDate = regDate;
    }
    public String getAge(){
        return age;
    }
    public void setAge(String age){
        this.age = age;
    }
}

 

반응형

4. db에 CRUD할 repository 작성

JpaRepository를 상속받고

@Repository 어노테이션을 적어준다.

여기서는 insert만 할거라 save만 적어줌

import kr.co.dominos.order.payment.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface MemberRepository extends JpaRepository<Member,String> {
    Member save(Member member);
}

 

5. controller로 테스트

import kr.co.dominos.order.payment.entity.Member;
import kr.co.dominos.order.payment.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


@RestController
@RequestMapping(value="api")
public class ApiController {

   @Autowired
    MemberRepository memberRepository;

   @Autowired
   Member member;

    @RequestMapping(method = RequestMethod.POST,path = "/save")
    public String savtest() {
        member.setAge("123123");
        Date today = new Date();
        member.setRegDate(today);

        try {
            memberRepository.save(member);
        }catch(Exception e){
            e.printStackTrace();
        }
        return "okok";
    }
}

 

이외에 다른 db config나 jpa config는 하지 않았음.

반응형

+ Recent posts