HQL更新查询

标签 hql

我在执行一个更新 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";
}

您能给我一些建议吗?应该如何处理这个查询:)?

最佳答案

来自the documentation :

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/

相关文章:

java - 添加到表后读取数据返回零

java - 具有两个角色的一个用户的输出

java - 通过 HQL 检索多对多集合和属性

java - 非法参数异常 : Could not locate named parameter

java - 如果一列中有空值,则无法获取行 hibernate hql

mysql - 如何将查询转换为hibernate查询语言?

java - HQL SELECT 子句不起作用

java - Hibernate:在多对一类映射中设置默认值

grails - 使用Grails避免HQL中的子查询

java - 错误 : org. hibernate.hql.internal.ast.ErrorCounter - 第 1:45 行:意外标记:从表中获取最后一条记录时的 DESC