Tina

Hibernate 설정

밍밍이

밍밍이

Apr 05, 2021

의존성 추가

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Model 만들기

@Entity
public class MDocument {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public MDocument() {
}
public MDocument(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MDocument [id=" + id + ", name=" + name + "]";
}
}

JpaRepository 상속한 Dao 만들기

JpaRepository를 상속해 만들면 JPA가 알아서 기본적인 CRUD를 만들어준다.

public interface DocDao extends JpaRepository<MDocument, Long>{
}

컨트롤러 만들기

@Controller
@RequestMapping(value = "/doc")
public class DocController {
@Autowired
private DocDao docDao;
@RequestMapping(value = "/saveDocAction")
@ResponseBody
public List<MDocument> saveDocAction(MDocument doc){
System.out.println(doc);
docDao.save(doc);
return docDao.findAll();
}
@RequestMapping(value = "/saveDoc")
public ModelAndView saveDoc() {
ModelAndView model = new ModelAndView();
MDocument doc = new MDocument();
model.addObject("doc", doc);
model.setViewName("doc/saveDoc");
return model;
}
}

뷰 만들기

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Save Doc</title>
</head>
<body>
<form action="#" th:action="@{/doc/saveDocAction}" th:object="${doc}" method="post">
<input type="text" th:field="*{name}" placeholder="name"/>
<input type="submit"/>
</form>
</body>
</html>

테이블 만들기

테스트

name 입력하고 제출을 누르면 saveDocAction이 호출되면서 데이터가 들어가야 한다.

에러 발생

java.sql.SQLException: Field 'id' doesn't have a default value

id의 기본값을 AUTO_INCREMENT로 바꿔준다.

다시 테스트

정상적으로 데이터가 입력되었다!

application.properties 설정

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
logging.level.org.hibernate.type.descriptor.sql=trace
  • dialect로 MariaDBDialect 추가 (JPA에 MariaDB 사용을 명시함.)
  • log에 sql문 추가
  • sql문을 보기 좋게 출력
  • sql문 이외 추가적인 정보 출력
  • sql문의 bind Parameter 출력