Hibernate 双向@ManyToOne,更新不拥有的一方不起作用 [英] Hibernate bidirectional @ManyToOne, updating the not owning side not working

查看:31
本文介绍了Hibernate 双向@ManyToOne,更新不拥有的一方不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的设置来尝试带注释的双向映射:

I have a really simple setup to try out a bidirectional mapping with annotations:

@Entity
public class TypeA extends AbstractModel<TypeA> {

    @Id
    @GeneratedValue
    private int id;

    @OneToMany(mappedBy="a")
    private Collection<TypeB> bs;

    // Getters & Setters ... 
}

@Entity
public class TypeB extends AbstractModel<TypeB> {

    private static final long serialVersionUID = -3526384868922938604L;

    @Id
    @GeneratedValue
    private int id;

    @ManyToOne()
    @JoinColumn(name="a_id")
    private TypeA a;
}

当我设置属性 TypeA.bs 时,虽然它应该影响映射,但它不会影响映射.请参见以下示例:

When I set the property TypeA.bs this does not affect the mapping, although it should. See the following example:

TypeB b = new TypeB();
this.typeBDao.save(b);

TypeA a = new TypeA();
a.setBs(ListUtils.createList(b));

System.out.println(a.getBs()); // output: [TypeB@25fe4d40]

this.typeADao.save(a);

System.out.println(a.getBs()); // output: [TypeB@25fe4d40]

this.typeADao.refresh(a);

System.out.println(a.getBs()); // output: []

this.typeBDao.refresh(b);
System.out.println(b.getA()); // output: null

如果映射是双向的,则应该填充集合并更新 b 的属性 a,但事实并非如此.有什么想法吗?

If the mapping is bidirectional, the collection should be populated and the property a of b should be updated, but it isnt. Any ideas?

编辑感谢大家的帮助,现在我明白了!

Edit Thanks for your help folks, now I got it!

推荐答案

对于一致的域模型,您应该始终设置关系的双方,如下所示:

For a consistent domain model you should always set both sides of the relation, like this:

TypeB b = new TypeB();

TypeA a = new TypeA();
a.setBs(ListUtils.createList(b));
b.setA(a);   

this.typeBDao.save(b);
this.typeADao.save(a);

当您的实体处于不一致状态时,JPA 将始终根据 JPA 关系的拥有方的对象状态存储值.在这种情况下,TypeB 拥有与 TypeA 的关系.因此,如果 TypeB 的对象没有对 TypeA 的引用,则 JPA 假定没有定义任何关系.

When your entities are in an inconsistent state, JPA will always store values according to the object state of the owning side of the JPA relation. In this case TypeB owns the relation to TypeA. Thus if an object of TypeB does not have a reference to TypeA, JPA assumes there is no relation defined.

这篇关于Hibernate 双向@ManyToOne,更新不拥有的一方不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆