本文介绍了休眠ManyToOne与OneToOne的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 我无法看到多对一关系模式与OneToOne关系模式的区别。 @Entity 
public class Order {

@ManyToOne
@JoinColumn(nullable = false)
私有地址;

vs

  @Entity 
public class Order {

@OneToOne
@JoinColumn(nullable = false)
私有地址;

是否有区别?

解决方案

它们在模式上看起来完全一样,但是在Hibernate Layer上有所不同。



如果您尝试类似这样的操作:

 地址address = new Address(); 
Order order1 = new Order();
order1.setAddress(address);
Order order2 = new Order();
order2.setAddress(address);
save();

一切都会好的。但是,保存后如果您尝试获取订单:

  @OneToOne案例:
org.hibernate.HibernateException:超过发现有一行有给定的标识符:1

@ManyToOne案例:
SUCCESS

当然,在这两种情况下,您的Address类应该看起来不同。


I can't see any difference in the schema of a Many-To-One relationship vs a OneToOne relationship:

@Entity
public class Order {

    @ManyToOne
    @JoinColumn(nullable = false)
    private Address address;

vs

@Entity
public class Order {

    @OneToOne
    @JoinColumn(nullable = false)
    private Address address;

Is there any difference?

解决方案

They look exactly the same on schema but there is difference on Hibernate Layer.

If you try something like that:

Address address = new Address();
Order order1 = new Order();
order1.setAddress(address);
Order order2 = new Order();
order2.setAddress(address);
save();

Everything will be OK. But, after save if you try get Order:

@OneToOne case:
org.hibernate.HibernateException: More than one row with the given identifier was found: 1

@ManyToOne case:
SUCCESS

Of course, your Address class should looks different in both cases.

这篇关于休眠ManyToOne与OneToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 18:05