How to persist two entities with JPA

后端 未结 2 1401
醉话见心
醉话见心 2020-12-03 16:18

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

相关标签:
2条回答
  • 2020-12-03 16:24

    You can persist one object and its child at a time. So I think this should work:

    ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg");  // create the picture object
    Consumer consumer = new Consumer("John Doe"); // create the consumer object
    consumer.setProfilePicture(profilePicture); 
    consumerFacade.create(consumer);
    
    0 讨论(0)
  • 2020-12-03 16:38

    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;
    }
    
    0 讨论(0)
提交回复
热议问题