如何使用 JPA 持久化两个实体 [英] How to persist two entities with JPA

查看:33
本文介绍了如何使用 JPA 持久化两个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 web 应用程序中使用 JPA,但我不知道如何保留两个相互关联的新实体.举个例子:

这是两个实体

<前>+-----------------+ +--------------------+|消费者 ||个人资料图片 |+-----------------+ +--------------------+|id (PK) |---|消费者 ID (PPK+FK)||用户名 ||网址 |+-----------------+ +--------------------+

Consumer 具有 id 和其他一些值.ProfilePicture 使用 消费者id 作为它自己的主键和外键.(因为没有 Consumer 就不会存在 ProfilePicture,并且不是每个 Consumer 都有 ProfilePicture)

我使用 NetBeans 生成实体类和会话 bean(外观).

简而言之,这就是它们的样子

Consumer.java

@Entity@Table(name = "消费者")@NamedQueries({...})公共类消费者实现可序列化{@ID@GeneratedValue(策略 = GenerationType.IDENTITY)@基本(可选=假)@Column(name = "id")私有整数 ID;@基本(可选=假)@NotNull@Size(min = 1, max = 50)@Column(name = "用户名")私人字符串用户名;@OneToOne(cascade = CascadeType.ALL,mappedBy = "consumer")私人 ProfilePicture profilePicture;/* 以及所有基本的 getter 和 setter */(...)}

ProfilePicture.java

@Entity@Table(name = "ProfilePicture")@XmlRootElement@NamedQueries({...})公共类 ProfilePicture 实现了 Serializable {@ID@基本(可选=假)@NotNull@Column(name = "consumerId")私人整数消费者ID;@基本(可选=假)@NotNull@Size(最小 = 1,最大 = 255)@Column(name = "url")私人字符串网址;@JoinColumn(name = "consumerId", referencedColumnName = "id", insertable = false, updatable = false)@OneToOne(可选=假)私人消费者;/* 以及所有基本的 getter 和 setter */(...)}

所以当我想用他的 ProfilePicture 创建一个 Consumer 时,我想我会这样做:

 ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg");//创建图片对象消费者消费者 = new Consumer("John Doe");//创建消费者对象profilePicture.setConsumer(消费者);//设置图片中的消费者(这样JPA可以处理关系consumerFacade.create(consumer);//持久化消费者的外观类profilePictureFacade.create(profilePicture);//当消费者被持久化(并且有一个 id)时,将图片持久化

我的问题

我尝试了几乎所有组合中的所有内容,但 JPA 似乎无法单独链接这两个实体.大多数时候我都会收到这样的错误:

 EJB5184:在 EJB ConsumerFacade 上调用期间发生系统异常,方法:public void com.me.db.resources.bean.ConsumerFacade.create(com.mintano.backendclientserver.db.resources.entity.Consumer)(...)对回调事件执行自动 Bean 验证时违反了 Bean 验证约束:'prePersist'.有关详细信息,请参阅嵌入式 ConstraintViolations.

据我所知,这是因为 ProfilePicture 不知道 Consumer 的 id,因此实体无法持久化.

它曾经工作的唯一方法是首先持久化 Consumer,将其 id 设置为 ProfilePicture,然后持久化图片:

 ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg");//创建图片对象消费者消费者 = new Consumer("John Doe");//创建消费者对象consumerFacade.create(consumer);//持久化消费者的外观类profilePicture.setConsumerId(consumer.getId());//在图片中设置消费者的新idprofilePictureFacade.create(profilePicture);//当消费者被持久化(并且有一个 id)时,将图片持久化

然而,这两个表只是一个例子,数据库自然要复杂得多,像这样手动设置 id 似乎非常不灵活,我担心事情会变得过于复杂.特别是因为我无法在一个事务中保留所有实体(这似乎效率很低).

我做得对吗?或者还有其他更标准的方法吗?

我的解决方案

正如 FTR 所建议的,一个问题是 ProfilePicture 缺少 id 表(我使用 Consumer.id 作为外部和主要)..

表格现在看起来像这样:

<前>+-----------------+ +--------------------+|消费者 ||个人资料图片 |+-----------------+ +--------------------+|id (PK) |_ |id (PK) ||用户名 |\_|消费者 ID (FK) |+---+ |网址 |+--------------------+

然后Alan Hay告诉我总是封装添加/删除到关系,然后你可以确保正确性,我做到了:

Consumer.java

public void addProfilePicture(ProfilePicture profilePicture) {profilePicture.setConsumerId(this);如果(profilePictureCollection == null){this.profilePictureCollection = new ArrayList<>();}this.profilePictureCollection.add(profilePicture);}

由于 ProfilePicture 现在有了自己的 id,它变成了 OneToMany 关系,因此现在每个 Consumer 可以拥有许多个人资料图片.这不是我一开始的意图,但我可以接受它:) 因此,我不能只为消费者设置 ProfilePicture,而是必须将其添加到图片集合中(如上).

这是我实现的唯一附加方法,现在它起作用了.再次感谢您的帮助!

解决方案

当持久化关系的非拥有方的实例(包含mappedBy",在您的情况下为 Consumer)时,您必须始终确保关系双方都按预期进行级联工作.

您当然应该始终这样做以确保您的域模型正确.

Consumer c = new Consumer();ProfilePicure p = new ProfilePicture();c.setProfilePicture(p);//看实现//持久化c

Consumer.java

 @Entity@Table(name = "消费者")@NamedQueries({...})公共类消费者实现可序列化{@ID@GeneratedValue(策略 = GenerationType.IDENTITY)@基本(可选=假)@Column(name = "id")私有整数 ID;@基本(可选=假)@NotNull@Size(min = 1, max = 50)@Column(name = "用户名")私人字符串用户名;@OneToOne(cascade = CascadeType.ALL,mappedBy = "consumer")私人 ProfilePicture profilePicture;public void setProfilePicture(ProfilePicture profilePicture){//设置关系的双方this.profilePicture = profilePicture;profilePicture.setConsumer(this);}}

始终封装添加/删除到关系,然后才能确保正确性:

公共类父{私人集<子>孩子们;公共集<子>获取儿童(){返回 Collections.unmodifiableSet(children);//没有直接访问:强制客户端使用添加/删除方法}public void addChild(Child child){child.setParent(this);孩子.添加(孩子);}公共类孩子(){私人父级;}

I am using the JPA in my webapp and I can't figure out how to persist two new entities that relate to each other. Here an example:

These are the two entities

+-----------------+   +--------------------+
|     Consumer    |   |   ProfilePicture   |
+-----------------+   +--------------------+
| id    (PK)      |---| consumerId (PPK+FK)|
| userName        |   | url                |
+-----------------+   +--------------------+

The Consumer has an id and some other values. The ProfilePicture uses the Consumer's id as it's own primary key and as foreign key. (Since a ProfilePicture will not exist without a Consumer and not every Consumer has a ProfilePicture)

I used NetBeans to generate the entity classes and the session beans (facades).

This is how they look like in short

Consumer.java

@Entity
@Table(name = "Consumer")
@NamedQueries({...})
public class Consumer implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "userName")
    private String userName;     

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "consumer")
    private ProfilePicture profilePicture;

    /* and all the basic getters and setters */
    (...)
}

ProfilePicture.java

@Entity
@Table(name = "ProfilePicture")
@XmlRootElement
@NamedQueries({...})
public class ProfilePicture implements Serializable {

    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "consumerId")
    private Integer consumerId;

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "url")
    private String url;

    @JoinColumn(name = "consumerId", referencedColumnName = "id", insertable = false, updatable = false)
    @OneToOne(optional = false)
    private Consumer consumer;

    /* and all the basic getters and setters */
    (...)
}

So when I want to create a Consumer with his ProfilePicture I thought I would do it like this:

   ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg");  // create the picture object
   Consumer consumer = new Consumer("John Doe"); // create the consumer object

   profilePicture.setConsumer(consumer);        // set the consumer in the picture (so JPA can take care about the relation      
   consumerFacade.create(consumer);             // the facade classes to persist the consumer
   profilePictureFacade.create(profilePicture);  // and when the consumer is persisted (and has an id) persist the picture

My Problem

I tried almost everything in every combination but JPA doesn't seem to be able to link the two entities on it's own. Most of the time I am getting errors like this:

 EJB5184:A system exception occurred during an invocation on EJB ConsumerFacade, method: public void com.me.db.resources.bean.ConsumerFacade.create(com.mintano.backendclientserver.db.resources.entity.Consumer)
 (...) 
Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.

As far as I understand the problem, it is because the ProfilePicture doesn't know the id of the Consumer and thus, the entities cannot persist.

The only way it ever worked, was when persisting the Consumer first, setting it's id to the ProfilePicture and then persisting the picture:

   ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg");  // create the picture object
   Consumer consumer = new Consumer("John Doe"); // create the consumer object

   consumerFacade.create(consumer);             // the facade classes to persist the consumer
   profilePicture.setConsumerId(consumer.getId()); // set the consumer's new id in the picture     

   profilePictureFacade.create(profilePicture);  // and when the consumer is persisted (and has an id) persist the picture

However these two tables are just an example and naturally the database is much more complex and setting the ids manually like this seems very inflexible and I am afraid of over complicating things. Especially because I can't persist all entities in one transaction (which seems very inefficient).

Am I doing it right? Or is there another, more standard way?

Edit: my solution

As FTR suggested, one problem was the missing id for the ProfilePicture table (I used the Consumer.id as foreign and primary)..

The tables look like this now:

+-----------------+   +--------------------+
|     Consumer    |   |   ProfilePicture   |
+-----------------+   +--------------------+
| id    (PK)      |_  | id (PK)            |
| userName        | \_| consumerId (FK)    |
+-----------------+   | url                |
                      +--------------------+

Then Alan Hay told me to Always encapsulate add/remove to relationships and then you can ensure correctness, which I did:

Consumer.java

public void addProfilePicture(ProfilePicture profilePicture) {
    profilePicture.setConsumerId(this);  
    if (profilePictureCollection == null) {
        this.profilePictureCollection = new ArrayList<>();
    }
    this.profilePictureCollection.add(profilePicture);
}

Since ProfilePicture has it's own id now, it became a OneToMany relationship, so each Consumer can now have many profile pictures. That's not what I intended at first, but I can life with it :) Therefore I can't just set a ProfilePicture to the Consumer but have to add it to a collection of Pictures (as above).

This was the only additional method I implemented and now it works. Thanks again for all your help!

解决方案

When persisting an instance of the non-owning side of the relationship (that which contains the 'mappedBy' and in your case Consumer) then you must always ensure both sides of the relationship are set to have cascading work as expected.

You should of course always do this anyway to ensure your domain model is correct.

Consumer c = new Consumer();
ProfilePicure p = new ProfilePicture();
c.setProfilePicture(p);//see implementation
//persist c

Consumer.java

    @Entity
    @Table(name = "Consumer")
    @NamedQueries({...})
    public class Consumer implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = "id")
        private Integer id;

        @Basic(optional = false)
        @NotNull
        @Size(min = 1, max = 50)
        @Column(name = "userName")
        private String userName;     

        @OneToOne(cascade = CascadeType.ALL, mappedBy = "consumer")
        private ProfilePicture profilePicture;

        public void setProfilePicture(ProfilePicture profilePicture){
            //SET BOTH SIDES OF THE RELATIONSHIP
            this.profilePicture = profilePicture;
            profilePicture.setConsumer(this);
        }
}

Always encapsulate add/remove to relationships and then you can ensure correctness:

public class Parent{
private Set<Child> children;

public Set<Child> getChildren(){
    return Collections.unmodifiableSet(children); //no direct access:force clients to use add/remove methods
}

public void addChild(Child child){
    child.setParent(this); 
    children.add(child);
}

public class Child(){
    private Parent parent;
}

这篇关于如何使用 JPA 持久化两个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆