2

I am currently developing a java ee application but i am having problems with the JPA. I have two entities:

@Entitiy
public class Restaurant implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Desk> desks;
}

@Entitiy
public class Desk implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "restaurant_id")
    private Restaurant restaurant;
}

And i am storing the desks with the following code:

Desk desk = new Desk();
desk.setNumber(Integer.toString(x));
desk.setRestaurant(restaurant);
em.persist(desk);

But now the strange thing is that the list of desks in the entity restaurant is empty but the restaurant value in the entity desk is correct. The Database shema looks like that:

RESTAURANT (ID)
DESK (ID, RESTAURANT_ID)
RESTAURANT_DESK (RESTAURANT_ID, DESK_ID)

The table RESTAURANT_DESK is always empty. Why is this third table generated? And why is the list of desks in the entity restaurant empty?

perotom
  • 851
  • 13
  • 33

2 Answers2

1

For a bi-directional mapping, you need to give mappedBy attribute in the Restaurant entity to indicate the inverse relationship:

@Entity
public class Restaurant implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="restaurant")
    private List<Desk> desks;
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Now the RESTAURANT_DESK will not be created but my list is still empty. Is the way to persist the desk wrong? – perotom Mar 29 '14 at 11:43
  • Which list are you talking about? Can you show some more code? – Rohit Jain Mar 29 '14 at 11:52
  • 1
    I guess you should set the both sides of the relationship. JPA only knows about the owning side of the relationship. `List` doesn't really exist in the database, it is rather mapped by `restaurant` in the `Desk` table. – Rohit Jain Mar 29 '14 at 11:57
  • Rohit Jain: I am talking about the List in the entity Restaurant. It is always empty. – perotom Mar 29 '14 at 11:58
0

I found the problem. I had to add the entity desk also to the restaurant list.

Desk desk = new Desk();
desk.setNumber(Integer.toString(x));
desk.setRestaurant(restaurant);
restaurant.getDesks().add(desk);
em.persist(desk);
perotom
  • 851
  • 13
  • 33