我在执行一个更新 HQL 查询时遇到问题。
我想编辑保存在个人资料实体中的值,但没有成功。
我的实体如下所示
@Entity
@Table(name = "users", catalog = "testdb")
public class UserEntity implements java.io.Serializable {
private Integer id;
private String username;
private String password;
private Profile profile;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
public Profile getProfile() {
return this.profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
@Entity
@Table(name = "profiles", catalog = "testdb")
public class Profile implements java.io.Serializable {
private Integer id;
private UserEntity user;
private String firstName;
private String lastName;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public UserEntity getUser() {
return this.user;
}
public void setUser(UserEntity user) {
this.user = user;
}
}
在 Controller 中我想执行以下更新查询:
@RequestMapping(value = "/profile", method = RequestMethod.POST)
public String profilePost(ModelMap model, @ModelAttribute("user") UserEntity user) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("update UserEntity u set u.profile.firstName = :firstName"
+ " where u.username = :username");
query.setParameter("firstname", "john");
query.setParameter("username", user.getUsername());
int result = query.executeUpdate();
session.getTransaction().commit();
return "redirect:/login";
}
您能给我一些建议吗?应该如何处理这个查询:)?
最佳答案
There can only be a single entity named in the from-clause. It can, however, be aliased. If the entity name is aliased, then any property references must be qualified using that alias. If the entity name is not aliased, then it is illegal for any property references to be qualified.
No joins, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.
像 Hibernate 这样的 ORM 的想法就是避免此类更新查询。您从 session 中获取持久实体,修改它,然后 Hibernate 透明地将更新保存到数据库:
Query query = session.createQuery("select p from Profile p where p.user.username = :username");
Profile p = query.setString("username", user.getUsername()).uniqueResult();
p.setFirstName("john");
关于HQL更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656993/