gpt4 book ai didi

HQL 更新查询

转载 作者:行者123 更新时间:2023-12-04 05:54:38 28 4
gpt4 key购买 nike

我有问题要执行一个更新 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com