[英]JPA save the transient instance before flushing
I have the following situation: a student belongs to a team, a team can have many students. 我有以下情况:一个学生属于一个团队,一个团队可以有很多学生。 At registration time the student doesn't know the assigned team, so the team object in student class should be null.
在注册时,学生不知道分配的团队,因此学生班级中的团队对象应为null。 How to force the insertion of student with null team object without getting this error:
如何在没有出现此错误的情况下强制使用空团队对象插入学生:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.af.domain.Student.team -> com.af.domain.Team
I tried cascade=CascadeType.ALL
but it also ads a new team in the database. 我尝试了
cascade=CascadeType.ALL
但是它还在数据库中为一个新团队做广告。
Student class 学生班
@Entity
@Table(name = "student")
public class Student implements DomainModel{
@Id
@GeneratedValue
private Integer idStudent;
private String firstname;
private String lastname;
private String username;
private String password;
@ManyToOne
@JoinColumn(name="idTeam", nullable=true)
private Team team;
}
Team class 团队班
@Entity
@Table
public class Team implements DomainModel{
@Id
@GeneratedValue
private Integer idTeam;
private String teamName;
@OneToMany(mappedBy="team")
private Set<Student> students;
}
Persistence class 坚持班
public class GenericDAOImpl<T extends DomainModel> implements GenericDAO<T> {
public void save(T object) {
EntityManager entityManager = entityManagerFactory
.createEntityManager();
entityManager.getTransaction().begin();
try {
entityManager.persist(object);
} catch(NullPointerException ex){
ex.printStackTrace();
}finally {
entityManager.getTransaction().commit();
entityManager.close();
}
}
}
You can use detach option with entity manager. 您可以将分离选项与实体管理器一起使用。 entityManager.detach --- This will detach that particular parent object from the main entity object which you want to persist or merge.
entityManager.detach ---这会将特定的父对象与您要保留或合并的主要实体对象分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.