持久化一个新对象而不必获取关联 [英] persisting a new object without having to fetch the associations
问题描述
我在一个广告实体中具有以下映射:
I have the following mapping in an Ad entity:
class Ad ... {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_ad_generator")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", nullable = false)
private Category category;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", nullable = false)
private City city;
在某个时候,我想保留一个新的广告...但是我只知道类别和城市的PK ID值(因为将实体转换为DTO,将其发送到存储ID的前端,然后将DTO发送到后端,其中包含类别和城市ID以及其他数据以构造广告)
At some point, I want to persist a new Ad... but i only know the PK id values for category and city (because the entities are converted to DTO's, send to the front end where the id's are stored, then a DTO is sent to the backend with the category and city id's and other data to construct the Ad)
要保留我要做的新广告:(em = EntityManager)
To persist the new ad i do: (em=EntityManager)
City city = em.find(City.class, city_id);
Category category = em.find(Category.class, category_id);
Ad ad = new Ad();
ad.setCity(city);
ad.setCategory(category);
ad.set(...otherstuff);
em.persist(ad);
很好,但是休眠状态是对城市进行选择,对类别进行选择,然后执行插入操作.如果我在SQL中执行此操作,并且知道ID是ID,那么我只会执行一条插入语句(事先没有选择内容)
that's fine and all, but hibernate performs a select for city and a select for category, then performs the insert. If I was doing this in SQL and I knew the id's I would just do an insert statement (no selects before hand)
那么,这是我做错的方式吗?还是这仅仅是ORM的本质
So, is this wrong the way I am doing it? Or is this just the nature of ORM
推荐答案
使用getReference
方法代替find
这篇关于持久化一个新对象而不必获取关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!