How to Define All Named Queries in One place (like class) instead of writing the NamedQuery in top of Entity class.
For Example i have a base class. In this class i can define all named queries.
Base.java
@Entity
@NamedQueries({
@NamedQuery(name="Student.findAll", query="SELECT s FROM Student s"),
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")})
class Base {
}
Assume now i have two entities like Student and Employee. Now i want to access the Named query from Base class. It is possible to access. If is possible then how.
class Employee {
}
class Student {
}
In employee class, Student i want to access the named query from Base class. It is possible. If it is possible how i can access.
query element is used for HQL named queries and sql-query element is used for native sql named queries. We can use return element for declaring the entity to which resultset will be mapped.
4. Named Native Query. As well as HQL queries, we can also define native SQL as a named query. To do this, we can use the @NamedNativeQuery annotation.
@NameQuery annotation is used to define the single named query.
Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client. Similar to how the constant is defined. NamedQuery is the way you define your query by giving it a name.
We did a similar thing on one project. We had one entity that contained all of our named queries and (as @jimfromsa already said) they are accessible to your code wherever you need them because you are calling them by their unique name.
@Entity
@NamedQueries({
@NamedQuery(name="Student.findAll", query="SELECT s FROM Student s"),
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e"),
...
@NamedQuery(name="SomeEntity.someQuery", query="SELECT se FROM SomeEntity se")
})
public class NamedQueryHolder implements Serializable {
// entity needs to have an id
@Id
private Integer id;
// getter and setter for id
}
Note that this entity doesn't need to be mapped to an existing table, as long as you don't use it anywhere in the code. At least this approach worked with EclipseLink, never tried it with Hibernate.
In your case, if you don't want this extra query holder entity, you can put all named queries in Base
class and it will work. However, I don't think it is a good idea to access named queries from your entity classes, they are called POJOs for a reason. Then again, it is all a matter of design (take a look at Anemic Domain Model).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With