JPA + hibernate外键为null

时间:2013-05-07 08:11:22

标签: java mysql hibernate jpa

我的数据库中有2个表。我有一个可以有多个版本的项目。一个构建属于一个项目。一切正常,除了我的构建表中的外键保持为空。

项目

@Entity(name="project")
public class Project implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "projectID")
private Long id;

@Column
@JsonProperty("displayName")
private String name;

@JsonProperty("builds")
@JsonIgnore
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("project"))
private Collection<Build> builds;

public Project() {
}

public Project(String name) {
    this.name = name;
}

public Collection<Build> getBuilds() {
    return builds;
}

public void setBuilds(Collection<Build> builds) {
    this.builds = builds;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}
}

构建

@Entity(name = "build")
public class Build implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
@JsonProperty("number")
private Integer number;

@Column
@JsonProperty("url")
private String url;

@JsonBackReference
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "project")
private Project project;

public Build() {
}

public Build(String url, Project project, Integer number) {
    this.url = url;
    this.project = project;
    this.number = number;
}

public Long getId() {
    return id;
}

public Integer getNumber() {
    return number;
}

public String getUrl() {
    return url;
}

public void setId(Long id) {
    this.id = id;
}

public void setNumber(Integer number) {
    this.number = number;
}

public void setUrl(String url) {
    this.url = url;
}

public Project getProject() {
    return project;
}

public void setProject(Project project) {
    this.project = project;
}
}

有没有人看到这个问题?

感谢。

1 个答案:

答案 0 :(得分:1)

使用JPA,您需要在Project对象中明确定义Build

Project project = new Project();

Build build = new Build();
build.setProject(project);

project.setBuilds(Collections.singletonList(build));

// now you can persist it    
em.persist(project)

来自Hibernate documentation

  

首先,请记住Hibernate不会影响普通的Java   语义。我们是如何在一个人和一个事件之间创建一个链接的   单向的例子?您将事件的实例添加到   Person实例的事件引用的集合。如果你想   要使这个链接双向,你必须在另一个上做同样的事情   通过在事件中添加对集合的Person引用。这个   “设置双方链接”的过程是绝对必要的   有双向链接。