JPA:如何创建与实体相同类型的字段?
问题描述:
我的类看起来像JPA:如何创建与实体相同类型的字段?
@Entity
public class Version extends MutableEntity {
@Column(nullable = false)
private String name;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private VersionType type;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private VersionStatus status;
@Column(nullable = true)
private DateTime publishedOn;
@Column(nullable = true)
private DateTime retiredOn;
@Column
private Version parentVersion;
我想有相同类型的parentVersion
作为Version
,但我的测试失败
@Test
public void testVersion() {
Version version = new Version("testVersion", VersionType.MAJOR);
version = crudService.create(version);
assertNotNull(version.getId());
}
,我看到错误的
Caused by: org.hibernate.MappingException: Could not determine type for: com.myorg.project.versioning.entities.Version, at table: Version, for columns: [org.hibernate.mapping.Column(parentVersion)]
哪有我解决了这个问题?
答
您在parentVersion
上缺少一些注释。 Hibernate不知道如何映射数据库中的这一列。
将@JoinColumn
添加到您的字段,hibernate将使用其@Id字段。
答
这不是基本属性。它是关系,因为价值是其他实体。因此@ManyToOne注释应使用:
@ManyToOne
private Version parentVersion;
如果需要双向关系(父知道儿童),即可以通过添加以下来完成:
@OneToMany (mappedBy = "parentVersion")
private List<Version> childVersions;