I have an entity class named "User", I want to store a list of data in User.
This is my code :
@Entity
public class User extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@Column(unique = true)
private String mail;
private String password;
private List<Feature> features;
}
And i have a Feature Class but its not a entity because it doesn't need to be an entity class, i think.
public class Feature {
private String fName;
private Long fYear;
}
When I start the application, I get an error:
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: java.util.List, at table: user, for columns: [org.hibernate.mapping.Column(features)]
CodePudding user response:
You can't insert list into SQL table, as a type.
You need to define relation(s):
@Entity
public class User extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@Column(unique = true)
private String mail;
private String password;
@OneToMany (or any other relation fitting your case)
private List<Feature> features;
}
and
@Entity
public class Feature {
@Id
//define generation strategy here
private long id;
private String fName;
private Long fYear;
}
CodePudding user response:
Since the Feature
type does hold instance fields that map to domain data, it should be saved as a separate entity.
If still the Feature
is out of your domain boundaries and does not need to be stored along the User
, you can mark it as being @Transient
and you may need to load its data based on your application semantics when loading a user entity.
Otherwise, you would go a the traditional path of mapping your entity:
@Entity
public class Feature extends BaseEntity {
// ...
@ManyToMany(mappedBy="features")
private Set<User> users = new HashSet<>();
// ...
}
Then you would need to define the User <> Feature
mapping:
@Entity
public class User extends BaseEntity {
// ...
@ManyToMany
@JoinTable(name="USER_FEATURE",
joinColumns=
@JoinColumn(name="USER_ID", referencedColumnName="ID"),
inverseJoinColumns=
@JoinColumn(name="FEATURE_ID", referencedColumnName="ID")
)
private Set<Feature> features = new HashSet<>();
// ...
}