有什么区别:
@Entity
public class Company {
@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
@JoinColumn(name = "companyIdRef", referencedColumnName = "companyId")
private List<Branch> branches;
...
}
Run Code Online (Sandbox Code Playgroud)
和
@Entity
public class Company {
@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY, mappedBy = "companyIdRef")
private List<Branch> branches;
...
}
Run Code Online (Sandbox Code Playgroud) 我在Parent和Child表之间有一对多的关系.在父对象中我有一个
List<Child> setChildren(List<Child> childs)
Run Code Online (Sandbox Code Playgroud)
我在Child表中也有一个外键.此外键是引用数据库中的父行的ID.所以在我的数据库配置中,这个外键不能为NULL.此外键也是Parent表中的主键.
所以我的问题是如何通过这样的方式自动保存子对象:
session.save(parent);
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的但我得到一个数据库错误抱怨Child表中的外键字段不能为NULL.有没有办法告诉JPA自动将此外键设置为Child对象,以便它可以自动保存子对象?
提前致谢.
我有1个用户到多个其他域并将其放在我的代码中:
用户类
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "USUARIO")
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID_USUARIO",unique = true,nullable = false)
private Long id;
@NotBlank(message = "usuario.cadastro.nome.obrigatorio")
@Column(name = "NOME", unique = true, nullable = false,length = 100)
private String nome;
@Email(message = "usuario.cadastro.email.invalido")
@Column(name = …Run Code Online (Sandbox Code Playgroud)