我在广告实体中有以下映射:
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 的本质
最佳答案
使用getReference
方法代替find
关于java - 在不必获取关联的情况下持久化一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3429979/