“分离的实体传递给持久性错误”使用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.
但我没有得到它,我需要修改什么才能使代码正常工作? / p>
But I didn't get it, what will I have to modify to get the code working?
推荐答案
假设你有两个实体专辑
和照片
。相册包含许多照片,因此它是一对多关系。
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;
}
在保持或合并之前你要做的就是设置每张照片中的相册参考。
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屋!