'JPA'에 해당되는 글 1건

  1. 2020.05.18 [spring boot]jpa 설정방법
server2020. 5. 18. 17:31

[spring boot]jpa 설정방법

 

properties

 

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://{아이피}:3306/{디비 이름}?serverTimezone=UTC&characterEncoding=UTF-8

spring.datasource.username={이름}

spring.datasource.password={비번}

 

spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect

spring.jpa.hibernate.ddl-auto=update

spring.jpa.generate-ddl= true

spring.jpa.show-sql = true

 

application

 

@EnableJpaRepositories(basePackages = "{package}") -> ex) com.aaa.bbb

 

위의 jpa repository package 안에서 해야 한다.

 

@Repository

public interface BoardRepository  extends JpaRepository<Board , Long>{

 

}

 

contoller

 

@RestController

public class UserController {

 

@Autowired

BoardRepository boardRepository;

 

@GetMapping("/create")

public String create()

{

Board board = new Board();

board.setTitle("title 2");

board.setContent("content 2");

board.setName("name 2");

 

 

boardRepository.save(board);

 

return "index";

}

 

@GetMapping("/all")

public List<Board> getAll()

{

return boardRepository.findAll();

}

}

 

--> create 호출하면 mysql 안에 db 생성 되고 , row값이 들어가고..

 

all 호출하면 부른다..

 

여기서 중요한건.. @RestController로 불러야 findAll의 배열이 json으로 변환되서 나온다.

 

server jpa model

 

@Entity

@Table(name="db_board")

public class Board {

 

@Id

@GeneratedValue

private Long id;

 

@Column(name="title", length =  100 , nullable = false)

private String title;

 

@Column(name="content", columnDefinition = "TEXT" , nullable = false)

private String content;

 

@Column(name="name")

private String name;

 

public Board()

{

 

}

 

public Long getId() {

return id;

}

 

public void setId(Long id) {

this.id = id;

}

 

public String getTitle() {

return title;

}

 

public void setTitle(String title) {

this.title = title;

}

 

public String getContent() {

return content;

}

 

public void setContent(String content) {

this.content = content;

}

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

}

 

pom.xml

 

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    </dependency>

    

   

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

Posted by thdeodls85