使用仅具有标识符的实体保存外键 [英] Saving a foreign key using entity with only id valorized

查看:99
本文介绍了使用仅具有标识符的实体保存外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个hibernate实体:

  @Entity 
class Company {
@Id
整数ID;
字符串名称;
}

@Entity
类Person {
整数id;
字符串名称;
@ManyToOne
公司公司;
}

我有一个已存储的公司,例如 Company(id :1,name:Acme)



我可以创建一个使用id而不是加载整个记录的公司的人员,例如:

  Session session = SessionFactory.openSession(); 
公司acme =新公司();
acme.setId(1);
Person person = new Person();
person.setName(Manuel);
person.setCompany(acme);

session.save(person);

它是只保存参考资料,还是用 name =

解决方案

是的,您可以做到。


它只保存参考资料,还是用
name = null更新公司


使用默认的 cascade ,就像那样,Hibernate将什么都不做。所以答案是:它只保存一个外键。



最有效的方法是使用 session.load(Company.class ,1)。它返回一个代理而不需要对数据库进行任何请求。但是,当然,您需要为它开会。


If I have two hibernate entities like:

@Entity
class Company {
     @Id
     Integer id;
     String name;
}

@Entity
class Person {
     Integer id;
     String name;
     @ManyToOne
     Company company;
}

I have an already stored company like Company(id:1, name:"Acme")

Can I create a person referencing the company with just its id instead of load the entire record, like:

Session session = SessionFactory.openSession();
Company acme = new Company();
acme.setId(1);
Person person = new Person();
person.setName("Manuel");
person.setCompany(acme);

session.save(person);

Does it save just the reference, or also update the company with name=null?

解决方案

Yes, you can do it.

Does it save just the reference, or also update the company with name=null?

With default cascade, like that, Hibernate will do nothing. So answer is: It saves just a foreign key.

The most valid (for JPA too) approach is using session.load(Company.class, 1). It returns a proxy without do any request to the database. But, you need to have a session for it, of course.

这篇关于使用仅具有标识符的实体保存外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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