<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
@Entitypublic 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;}@Overridepublic String toString() {return "MDocument [id=" + id + ", name=" + name + "]";}}
JpaRepository를 상속해 만들면 JPA가 알아서 기본적인 CRUD를 만들어준다.
public interface DocDao extends JpaRepository<MDocument, Long>{}
@Controller@RequestMapping(value = "/doc")public class DocController {@Autowiredprivate DocDao docDao;@RequestMapping(value = "/saveDocAction")@ResponseBodypublic 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
로 바꿔준다.
정상적으로 데이터가 입력되었다!
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialectspring.jpa.properties.hibernate.show_sql=truespring.jpa.properties.hibernate.format_sql=truespring.jpa.properties.hibernate.use_sql_comments=truelogging.level.org.hibernate.type.descriptor.sql=trace