我在广告实体中有以下映射:
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以及构建广告的其他数据
要保留新广告:(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);
这很好,但是hibernate执行城市选择和类别选择,然后执行插入。如果我在SQL中执行此操作并且我知道id我将只执行一个插入语句(之前没有选择)
那么,这样做是错误的吗?或者这只是ORM的本质
答案 0 :(得分:6)
使用getReference
方法代替find