1

I java ee project with two entity classes: Employee and Shift, and there's a many to many reletaionship between them. It looks like this:



    @Entity
    public class Employee implements Serializable {
    @ManyToMany(mappedBy="employees")
    private List shifts;
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String surname;
    private String firstname;


...



    @Entity

    public class Shift implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date timeStart;
    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date timeEnd;
    private int workers;
    private int overseers;
    @ManyToMany
    private List employees;

I have a JSF page where i would like to add employees (one by one) to the selected shift so in my backing bean theres this method:



    public void addToShift(Employee e){
            selectedShift.addEmployee(e);
            e.addShift(selectedShift);      
    }

After the method is called, i see nothing in the join table. I tried a few things, like looking up the entities again using entitymanager.find, but nothing really helped, i can't see anything in the join table and i can't see why. There were no problem managing employees and shift, it's "just" the connection... Do you have any ideas?

4

1 回答 1

1

Simply setting values to detached entities is not enough. You still have to call EntityManager.merge inside transaction. Then after when transaction is committed (or entitymanager is flushed) you will see results in database as well.

When persistence context is still open (which it is not in your case), flush alone is enough and merging is not needed.

于 2012-05-10T18:34:04.113 回答