Search code examples
javamysqljpajakarta-eepayara

How to persist a property of type List<Object> in JPA?


What is the best way to get a List with Objects persisted? I'm using JavaEE 7 with JPA. Object B is also an Entity.

My Model

@Entity
public class ObjectA implements Serializable {

    @Id @GeneratedValue
    private Long id;

    // What should I use here?
    private List<ObjectB> objectList;

    public ObjectA () {
        this.objectList = new ArrayList<ObjectB>();
    }
}

My JPA Calls

@Stateless
@JPA
public class ObjectJPA{

    @PersistenceContext(unitName = "ObjectProjectPU")
    private EntityManager em;

    // How can I insert a record in the table for objectList here?
    public void insertIntoObjectList(ObjectB objectB) {
        em.persist(objectB); // This must be wrong?
    }
}

What I prefer is that my database table for objectList would look like this:

id (ObjectA_id) | objectB_id     or    id | ObjectA_id | objectB_id

Solution

  • I figured out that it was pretty easy.

    ObjectA Model

    @OneToMany
    @JoinTable
    (
        name="OBJECTA_OBJECTB",
        joinColumns={ @JoinColumn(name="ID", referencedColumnName="ID") },
        inverseJoinColumns={ @JoinColumn(name="OBJECTB_ID", referencedColumnName="ID") }
    )
    private List<ObjectB> objectList;
    

    JPA CALL

    public void insertIntoObjectList(ObjectB object) {
        object.setSomeDataInObjectList(list); // just a random list here
        em.persist(object); 
    }
    

    ObjectB Model

    @ManyToOne
    ObjectA objectA;