“传递给持久性错误的分离实体"带有 JPA/EJB 代码 [英] "detached entity passed to persist error" with JPA/EJB code
问题描述
我正在尝试运行这个基本的 JPA/EJB 代码:
I am trying to run this basic JPA/EJB code:
public static void main(String[] args){
UserBean user = new UserBean();
user.setId(1);
user.setUserName("name1");
user.setPassword("passwd1");
em.persist(user);
}
我收到此错误:
javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.JPA.Database
有什么想法吗?
我在互联网上搜索,我发现的原因是:
I search on the internet and the reason I found was:
这是由您创建对象的方式引起的,即如果您显式设置了 ID 属性.删除 ID 分配修复了它.
This was caused by how you created the objects, i.e. If you set the ID property explicitly. Removing ID assignment fixed it.
但我没有明白,我需要修改什么才能使代码正常工作?
But I didn't get it, what will I have to modify to get the code working?
推荐答案
假设您有两个实体 Album
和 Photo
.相册里有很多照片,所以是一对多的关系.
Let's say you have two entities Album
and Photo
. Album contains many photos, so it's a one to many relationship.
相册类
@Entity
public class Album {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Integer albumId;
String albumName;
@OneToMany(targetEntity=Photo.class,mappedBy="album",cascade={CascadeType.ALL},orphanRemoval=true)
Set<Photo> photos = new HashSet<Photo>();
}
照片类
@Entity
public class Photo{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Integer photo_id;
String photoName;
@ManyToOne(targetEntity=Album.class)
@JoinColumn(name="album_id")
Album album;
}
在persist或merge之前需要做的是在每张照片中设置相册引用.
What you have to do before persist or merge is to set the Album reference in each photos.
Album myAlbum = new Album();
Photo photo1 = new Photo();
Photo photo2 = new Photo();
photo1.setAlbum(myAlbum);
photo2.setAlbum(myAlbum);
这就是在持久化或合并之前如何附加相关实体.
That is how to attach the related entity before you persist or merge.
这篇关于“传递给持久性错误的分离实体"带有 JPA/EJB 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!