【问题标题】:How do I get an auto-generated value?如何获得自动生成的值?
【发布时间】:2010-10-22 02:47:54
【问题描述】:
@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”列中设置了null? 如何获取在First 中的a 中自动创建的值以在b 中的Second 中设置?

【问题讨论】:

    标签: jpa


    【解决方案1】:

    有几点:

    First:您不需要在 First 类中的 seconds 集合上添加 @JoinColumn(name = "a") 注释。映射由 Second 类处理。

    下一步:

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

    【讨论】:

    • 我可以问第二个问题吗?如果我想在其主键“a”而不是“b”上加入第二个表怎么办:@ManyToOne @JoinColumn(name = "a", insertable = false, updatable = false) First first;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2020-12-06
    • 2022-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多