2

我的数据库中有 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;
}
}

有没有人看到问题?

4

1 回答 1

1

Project使用 JPA,您需要在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 不会影响正常的 Java 语义。在单向示例中,我们如何在 Person 和 Event 之间创建链接?您将 Event 实例添加到 Person 实例的事件引用集合中。如果要使此链接双向,则必须在另一端执行相同操作,方法是在 Event 中添加对集合的 Person 引用。这种“在两边设置链接”的过程对于双向链接是绝对必要的。

于 2013-05-07T08:16:03.927 回答