본문 바로가기
spring/JPA

Jpa로 게시물(1)

by coie 2021. 5. 25.

기존에 스프링 Legacy만 이용하다가

스프링 부트도 해보고 싶고 JPA도 해보고 싶고

인텔리j도 사용해보고싶어서

공부도 할 겸 공부하면서 익혀가면서 작성해보겠습니다.

 

먼저 

 

와 같이 해서 생성을 해준 뒤,

 

application.properties

server.port = 8081

# db설정
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=[]
spring.datasource.password=[]

# JPA
spring.jpa.hibernate.ddl-auto=create(후에 update로 수정해줍니다.)
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.database=oracle

와 같이 설정을 해주면 되는데

spring.jpa.hibernate.ddl-auto를 후에 update로 바꿔주는 이유는

처음에는 create를 하면 따로 DB를 생성 안해줘도

자동으로 생성이 됬습니다.

그런데 중간 중간에 오류가 발생해서 다시 실행시키는 과정에서

'not-null property references a null or transient value'

오류가 발생해서

UPDATE로 수정하니 제대로 작동했습니다.

 

그 후

위와 같이 구성을 합니다.

 

PostEntity

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Getter
@Table(name = "POST")
public class PostEntity{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(nullable = false)
    private String title;
    @Column(nullable = false)
    private String content;
    @Column(nullable = false)
    private String writer;

    @Builder
    public PostEntity(Long id,String title,String content,String writer){
        this.id = id;
        this.title=title;
        this.content=content;
        this.writer=writer;
    }


}

와 같이 작성해줍니다.

기존에는 

@GeneratedValue(strategy = GenerationType.AUTO)

가 아닌 sequence를 해줬는데

auto는 JPA가 자동으로 할당해준다.

 

그 다음은 

PostRepository이다.

public interface PostRepository extends JpaRepository<PostEntity,Long> {
}

Repository는 JpaRepository를 상속만 받아주면 된다.

만약 본인이 원하는 새로운 쿼리 기능이 필요할 때

작성해주면 된다.

 

다음은 PostDto

import com.example.board.Domain.Entity.PostEntity;
import lombok.*;

@Getter
@Setter
@ToString
@NoArgsConstructor
public class PostDto {

    private Long id;
    private String writer;
    private String title;
    private String content;

    public PostEntity toEntity(){
        PostEntity postEntity = PostEntity.builder().
                id(id).
                title(title).
                content(content).
                writer(writer).
                build();
        return postEntity;
    }

    @Builder
    public PostDto(Long id,String title,String content,String writer){
        this.id = id;
        this.title=title;
        this.content=content;
        this.writer=writer;
    }
}

Dto를 보면 기존의 Entity와 거의 같습니다.

그냥 공부하면서 느낀 것은 Entity는 테이블과 매핑하는 객체인데 이걸 

중간에 데이터를 이동시키는 객체로 맞나? 라고 생각하고

그에 대하여 Dto를 이용하는 것이다.

구글에서 가져온 사진인데

위 와같이 Dto를 이용해서 데이터를 이동시키고 마지막 DB에는 Entity를 넣는 것으로 이해하면 된다.

 

다음은 PostService

@Service
@AllArgsConstructor
public class PostService {

    private PostRepository postRepository;

    @Transactional
    public Long writepost(PostDto postDto){

        return postRepository.save(postDto.toEntity()).getId();
    }

}

return의 save는 JpaRepository에 기본적으로 있는 것.

 

마지막으로 

PostController

@Controller
@AllArgsConstructor
public class PostController {

    private PostService postService;

    @GetMapping("/")
    public String list(){
        return "post/list.html";
    }

    @GetMapping("/post")
    public String postwrite(){
        return "post/write.html";
    }

    @PostMapping("/post")
    public String postwrite(PostDto postDto){

        postService.writepost(postDto);

        return "post/list.html";
    }
}

아직 글 작성후 

맨처음 화면으로 갈지 못정해서

임의로 설정해놨는데

redirect:/ 로 해도 된다.

 

이 다음으로 타임리프를 이용하여

list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a th:href="@{/post}">글쓰기</a>

</body>
</html>

write.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form  action="/post" method="post">
    제목 : <input type="text" name="title"> <br>
    작성자 : <input type="text" name="writer"> <br>
    <textarea name="content"></textarea><br>

    <input type="submit" value="등록">
</form>
</body>
</html>

css하나 없이 

아주 기본적인 틀이다.

 

 

이 후 스프링 부트를 실행 시킨 후

http://localhost:8081 로 접속

이렇게 작성을 한후 

확인을 해보면

이렇게 insert된 것을 확인 할 수 있다.

 

'spring > JPA' 카테고리의 다른 글

JPA/Dto?Entity?  (0) 2021.05.22
JPARepository  (0) 2021.05.21
JPAEntity  (0) 2021.05.21