如何获得自动生成的值?

时间:2009-04-27 16:56:00

标签: jpa

@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;
}

当我在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();

在表格第二列的“b”栏中设置为空? 如何在a中的First中设置自动创建的值,以便在b的{​​{1}}中设置?

1 个答案:

答案 0 :(得分:1)

有几件事:

首先:在First类的seconds集合中不需要@JoinColumn(name =“a”)注释。映射由第二类处理。

下一步:

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();