📅  最后修改于: 2023-12-03 15:15:32.669000             🧑  作者: Mango
With HQL, you can easily query your database using simple, readable queries. HQL queries are also database-independent, so you don't have to worry about writing queries that are specific to a particular database.
Creating objects with constructor expressions can be useful in situations where you need to create temporary objects that you don't want to store in the database.
Let's see an example of using Constructor expressions in HQL queries:
Query query = session.createQuery("SELECT NEW com.example.UserDTO(u.id, u.name, u.email) FROM User u");
List<UserDTO> users = query.list();
In the above example, we are selecting users from the User table and creating a new UserDTO object using the constructor. The UserDTO object has three attributes: id, name, and email.
Here's an example of using Constructor expressions in HQL queries:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
// getters and setters
}
public class UserDTO {
private Long id;
private String name;
private String email;
public UserDTO(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// getters and setters
}
// using Constructor expressions in HQL queries
Query query = session.createQuery("SELECT NEW com.example.UserDTO(u.id, u.name, u.email) FROM User u");
List<UserDTO> users = query.list();
In the above code, we have an Entity class, User, that has three attributes: id, name, and email. We also have a UserDTO class that has the same attributes as User but in a different format.
We then use a Constructor expression in the HQL query to create a new UserDTO object with the id, name, and email attributes from the User object.
Finally, we execute the query and get a List of UserDTO objects.