Mapping a list of child objects in JPA - one to many

133 Views Asked by At

I am developing my first application using JPA. There I have a requirement that the parent object has a list of child objects and that list is not separately entered to its table.

Here are my Entities.

Tender :-

@Entity
@Table(name = "tender")
public class Tender {

    @Id
    @Column(name = "tender_id", unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    // what are the annotations here?
    private List<TenderAddress> addresses;

    // constructors

    // getters ans setters

}

TenderAddress :-

@Entity
@Table(name = "tender_address")
public class TenderAddress {

    @Id
    @Column(name = "id", unique = true, nullable = false)
    @GeneratedValue
    private long id;

    // what are the annotations here?
    private Tender tender;

    @Column(name = "address", nullable = false)
    private String address;

    // constructors 

    //getters and setters

}

I set addresses to the tender object using the setter method of the tender. This is how I save the Tender objects to the database. I use entity manager for that.

@Transactional
public Tender saveNewTender(Tender tender) {            
        entityManager.persist(tender);

        entityManager.flush();

        return tender;
}

What I need is to save the Address entity at the same time and the address table to have a reference to the tender object which encapsulates the particular address.

I tried with bidirectional one to many mapping using @JoinColumn and @OneToMany(mappedBy="tender", cascade = CascadeType.ALL). But it marked the reference column to NULL(tender id field in the Address table)

Now my question is, is my requirement valid? Do I have to persist the tender object first and take the id of it and then persist the Address object?

If my requirement is valid, how can I get it implemented? What can you recommend me? Please provide me the annotations I need in my entities.

0

There are 0 best solutions below