当我尝试保存实体
时@Autowired
private GenericDao<ProfileRoles, Integer> gProfileRolesDao;
...
gProfileRolesDao.create(new ProfileRoles(new Profile(idProfile), new Role(role)));
使用create
@Repository
public class GenericDao<T, PK extends Serializable> {
@PersistenceContext
private EntityManager entityManager;
...
public T create(T t) {
this.entityManager.persist(t);
return t;
}
和ProfileRoles
实体
@Entity
@Table(name="profile_roles")
public class ProfileRoles {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "profile")
private Profile profile;
@ManyToOne
@JoinColumn(name = "role")
private Role role;
一切都很好,但我得到了额外的选择
Hibernate: select role_.id, role_.label as label2_22_ from role role_ where role_.id=?
Hibernate: insert into profile_roles (profile, role) values (?, ?)
如何优化它?
这是一个讨论,而不是在此阶段的答案,但是对代码示例的评论不仅仅是评论...
快速测试,将new Role(existingRoleId)
分配给ProfileRole
工作正常,没有额外的选择role
表。
额外的选择可以指向保存或合并role
的东西。选择冬眠后,没有发现需要更新回到数据库的更改。
追踪角色选择的内容的直接方法是Role
上的@PostLoad
方法。例如,它可能会丢弃当前的堆栈跟踪:
@PostLoad
public void postLoad() {
new Exception("Post-load trace stack").printStackTrace();
}
幸运的是,这将提供潜在客户。
一般而言,为避免创建具有多一相关实体的实体时额外的选择,首先,您应该为其获得参考。
因此,在您的情况下,您应该使用Profile
和Role
的参考(如果您还没有它们(,然后与它们创建ProfileRoles
,例如:
// begin transaction
Profile profile = entityManager.getReference(Profile.class, profileId);
Role role = entityManager.getReference(Role.class, roleId);
entityManager.persist(new ProfileRoles(profile, role))
// commit
更多信息:使用JPA和Hibernate