I have an Entity like this:
@Entity
@Data
public class Cat {
@Id
private String catId;
private String catName;
private List<String> favFoods;
}
When I start my Spring boot, it shows this error:
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: java.util.List
I drop the table Cat in DB before starting the app My yml setting is:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/localtest
username: catuser
password:
jpa:
show-sql: false
hibernate:
ddl-auto: create
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
If I comment out the field of List, everything works fine. Is there any annotation that I need to add to solve this problem?
Thank you
CodePudding user response:
You have to tell Hibernate how to map the list by annotating you class with @TypeDef(name = "list-array",typeClass = ListArrayType.class)
and annotating the list with @Type(type = "list-array")
i.e.:
@Entity
@Data
@TypeDef(
name = "list-array",
typeClass = ListArrayType.class
)
public class Cat {
@Id
private String catId;
private String catName;
@Type(type = "list-array")
private List<String> favFoods;
}
CodePudding user response:
You can also use the following code snippet
@ElementCollection
@CollectionTable(name = "my_list", joinColumns = @JoinColumn(name =
"id"))
@Column(name = "list")
List<String> favFoods;
See here