tags:

views:

191

answers:

1
@TableGenerator(name = "trial", table = "third",
        pkColumnName = "a" , valueColumnName = "b", pkColumnValue = "first")

@Entity

public class First{

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "trial")
    protected int a;

    @OneToMany(mappedBy ="first", cascade = CascadeType.PERSIST)
    @JoinColumn(name = "a")
    protected List<Second> seconds;
}

@Entity

public class Second{

    @Id
    protected int a;

    @ManyToOne
    @JoinColumn(name = "b")
    First first;
}

When I run the following in main:

Second aSecond = new Second();

aSecond.a = 2;

First aFirst = new First();

List<Second> scnds = new ArrayList<Second>();
scnds.add(aSecond);

aFirst.seconds = scnds;

aEntityManager.getTransaction().begin();

aEntityManager.persist(aFirst);

aEntityManager.getTransaction().commit();

It set null in the column "b" in table second? How can I get the value that is auto-created in a in First to set in b in Second?

+1  A: 

A couple of things:

First: You do not need the @JoinColumn(name = "a") annotation on the seconds collection in the First class. The mapping is being handled by the Second class.

Next:

Second aSecond = new Second();
aSecond.a = 2;
First aFirst = new First();

//its a bi-directional mapping so you have to set the references both ways
aFirst.seconds.add(aSecond);
aSecond.first = aFirst;

aEntityManager.getTransaction().begin();
aEntityManager.persist(aFirst);
aEntityManager.getTransaction().commit();
Vincent Ramdhanie
Could I ask second question? What if I want to join Second table on its primary key "a" instead of "b" with: @ManyToOne @JoinColumn(name = "a", insertable = false, updatable = false) First first;
Moro