问题
I've got problem to exceute one update-HQL-query.
I want to edit values saved in profile entity, but with no luck.
my entities looks like below
@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;
}
}
In controller I want to execute the following update query:
@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";
}
could You give me some advice how should lok this query:)?
回答1:
From 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.
The idea of an ORM like Hibernate is to avoid such update queries. You get a persistent entity from the session, you modify it, and Hibernate transparently saves the updates to the database:
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");
来源:https://stackoverflow.com/questions/9656993/hql-update-query