I have a tiny spring boot application (it is just a proof of concept) running against an H2 in-memory DB and using spring-data-jpa to handle persistence. It consists of a REST API that allows handling posts and comments, so you can create and retrieve posts and comments on those posts.
The application has two JPA entities Post and Comment, and the problem that I'm facing is that after adding Comment entity, the application fails to start, but before adding Comment when I just had the Post entity the application started and tests passed. It seems that spring boot is not being able to properly autoconfigure JPA.
This is the error I get:
[ERROR] shouldReturnNullForNotExistingPost(com.devskiller.tasks.blog.service.PostServiceTest) Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.devskiller.tasks.blog.model.Post, at table: comment, for columns: [org.hibernate.mapping.Column(post)]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.devskiller.tasks.blog.model.Post, at table: comment, for columns: [org.hibernate.mapping.Column(post)]
Caused by: org.hibernate.MappingException: Could not determine type for: com.devskiller.tasks.blog.model.Post, at table: comment, for columns: [org.hibernate.mapping.Column(post)]
Post entity:
@Entity
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@Column(length = 4096)
private String content;
private LocalDateTime creationDate;
// Getters and setters
Comment entity:
@Entity
public class Comment {
@Id
@GeneratedValue
private Long id;
private String author;
private String content;
private Post post;
// Getters and setters
Solution:
After adding @OneToOne annotation to Comment.post field the error disappears. But why? I thought that according to JPA spec, it's not necessary to add this annotation in order to create the unidirectional relationship between the two entities with default configuration. Isn't it?