何时使用,不使用OneToOne和ManyToOne [英] When to use, not to use, OneToOne and ManyToOne

查看:519
本文介绍了何时使用,不使用OneToOne和ManyToOne的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始阅读JPA,并在hibernate中实现了解细节。但是,为了继续发展到那时,你能帮助澄清一个基本的qn。

I just started reading of JPA, and the implementation in hibernate to understand the details. but, to continue with development till then, can you help to clarify a basic qn.


  1. 何时使用OneToOne

    如果实体经理需要处理持久性,我可以使用OneToOne相关的对象。关键是,我总是可以在不指定oneToOne的情况下生活,但是我有责任管理关系并确保引用的对象不处于瞬态状态。这是真的吗?

  1. When to use OneToOne
    I may use OneToOne if the entity manager needs to handle the persistency of the related object. the point is, I can always live without specifying oneToOne, but then the responsibility is on me to manage the relationship and making sure that the referred objects are not in transient state. Is this true?

何时使用或不使用,ManyToOne

假设我正在定义一个Employee类,并且需要使用雇主定义rel。在这种情况下,我是否需要指定manyToOne,如下所示,或者如果不是

When to use, or not to use, ManyToOne
Say I am defining an Employee class, and needs to define the rel with Employer. In this case, do I need to specify manyToOne like below, or what if not

 @Entity   
    public class Employer {  
    String name;   
    }   

    @Entity   
    class Employee {  
        String name;  
        @ManytoOne  //or not??   
        Employer employer;   
        }


谢谢

推荐答案

1:使用实体关系时,必须始终使用相应的注释(OneToOne,OneToMany,ManyToOne ,或ManyToMany)。您的选择是您是否要确保关系背后的实体本身不是瞬态的,或者指定级联属性让JPA为您处理。这允许您创建一个完整的对象图并在一次调用中保留它们:

1: When working with entity relations, you must always use the appropriate annotations (OneToOne, OneToMany, ManyToOne, or ManyToMany). The choice you have is whether you want to make sure the entity behind the relation is not transient yourself, or specify the cascade property on the OneToOne annotation to let JPA take care of that for you. This allows you to create a whole graph of objects and persist them in one call:

@OneToOne(cascade = CascadeType.ALL)
private MyType myType;

2:是的,雇主 - 雇员关系听起来像OneToMany关系,雇员与雇主的关系将是ManyToOne。如果您想要两个方向,那就称为双向关系。查看 Java EE教程中的相关部分详情。

2: Yes, an employer-employee relationship sounds like a OneToMany relationship, and the employee-employer relationship would be ManyToOne. If you'd like to have both directions, that's called a bi-directional relationship. Have a look at the relevant section in the Java EE tutorial for details.

Java EE教程中的JPA部分是一个很好的参考资料。

The JPA section in the Java EE tutorial is a good reference to start from.

这篇关于何时使用,不使用OneToOne和ManyToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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