Code ví dụ Hibernate Named Query (annotation @NamedQuery, @NameQueries)
Hibernate Named Query
Hibernate Named Query được sử dụng để cung cấp các câu query dùng chung. Việc sử dụng các query chung như này giúp chúng ta dễ maintain hơn (khi yêu cầu thay đổi câu query, ta chỉ cần sửa ở 1 nơi)
Ưu điểm: Named Query được compile và validate khi ứng dụng được start, dễ dàng maintain hơn các câu SQL viết lẫn vào với code nhất là các câu SQL phức tạp.
Các công nghệ sử dụng trong ví dụ
Tạo database trên MySQL
Trong ví dụ này mình tạo cơ sở dữ liệu ‘hibernate-demo’ với table customer (id, name, address) trong đó id tự tăng.
CREATE DATABASE IF NOT EXISTS `hibernate-demo`;
CREATE TABLE `hibernate-demo`.`customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
- CREATE DATABASE IF NOT EXISTS `hibernate-demo`;
- CREATE TABLE `hibernate-demo`.`customer` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(45) DEFAULT NULL,
- `address` varchar(255) DEFAULT NULL,
- PRIMARY KEY (`id`)
- );
CREATE DATABASE IF NOT EXISTS `hibernate-demo`;
CREATE TABLE `hibernate-demo`.`customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Khởi tạo dữ liệu ban đầu:
INSERT INTO `customer` VALUES (1,'Kai','Viet Nam');
INSERT INTO `customer` VALUES (2,'Thanos','Titan');
INSERT INTO `customer` VALUES (3,'Thor','Asgard');
INSERT INTO `customer` VALUES (4,'Hulk','USA');
INSERT INTO `customer` VALUES (5,'Iron Man','USA');
- INSERT INTO `customer` VALUES (1,'Kai','Viet Nam');
- INSERT INTO `customer` VALUES (2,'Thanos','Titan');
- INSERT INTO `customer` VALUES (3,'Thor','Asgard');
- INSERT INTO `customer` VALUES (4,'Hulk','USA');
- INSERT INTO `customer` VALUES (5,'Iron Man','USA');
INSERT INTO `customer` VALUES (1,'Kai','Viet Nam');
INSERT INTO `customer` VALUES (2,'Thanos','Titan');
INSERT INTO `customer` VALUES (3,'Thor','Asgard');
INSERT INTO `customer` VALUES (4,'Hulk','USA');
INSERT INTO `customer` VALUES (5,'Iron Man','USA');
Tạo Maven Project
Ở đây mình sẽ sử dụng Named Query với cả EntityManager và Session
Thư viện sử dụng
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>stackjava.com</groupId>
- <artifactId>HibernateNamedQuery</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <properties>
- <hibernate.version>5.1.0.Final</hibernate.version>
- </properties>
- <dependencies>
- <!-- Hibernate -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <version>${hibernate.version}</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-entitymanager</artifactId>
- <version>${hibernate.version}</version>
- </dependency>
- <!-- MySQL JDBC driver -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.46</version>
- </dependency>
- </dependencies>
- </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackjava.com</groupId>
<artifactId>HibernateNamedQuery</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<hibernate.version>5.1.0.Final</hibernate.version>
</properties>
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MySQL JDBC driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackjava.com</groupId>
<artifactId>HibernateNamedQuery</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<hibernate.version>5.1.0.Final</hibernate.version>
</properties>
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MySQL JDBC driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project>
File cấu hình hibernate – SessionFactory
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate-demo?useSSL=false</property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password">admin1234</property>
- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="hibernate.hibernate.current_session_context_class">thread</property>
-
- <mapping class="stackjava.com.hibernatenamedquery.model.Customer" />
- </session-factory>
- </hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate-demo?useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin1234</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hibernate.current_session_context_class">thread</property>
<mapping class="stackjava.com.hibernatenamedquery.model.Customer" />
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate-demo?useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin1234</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hibernate.current_session_context_class">thread</property>
<mapping class="stackjava.com.hibernatenamedquery.model.Customer" />
</session-factory>
</hibernate-configuration>
File cấu hình jpa – EntityManagerFactory
- <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
- http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
- <persistence-unit name="persistence">
- <description>Demo Hibernate Entity Manager</description>
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <properties>
- <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
- <property name="javax.persistence.jdbc.url"
- value="jdbc:mysql://localhost:3306/hibernate-demo" />
- <property name="javax.persistence.jdbc.user" value="root" />
- <property name="javax.persistence.jdbc.password" value="admin1234" />
- <property name="hibernate.show_sql" value="false" />
- </properties>
- </persistence-unit>
- </persistence>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<persistence-unit name="persistence">
<description>Demo Hibernate Entity Manager</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/hibernate-demo" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="admin1234" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<persistence-unit name="persistence">
<description>Demo Hibernate Entity Manager</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/hibernate-demo" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="admin1234" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
File entity
- package stackjava.com.hibernatenamedquery.model;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.NamedQueries;
- import javax.persistence.NamedQuery;
- import javax.persistence.Table;
- @Entity
- @Table(name = "customer")
- @NamedQueries({
- @NamedQuery(name = "Customer.FIND_ALL", query = "FROM Customer"),
- @NamedQuery(name = "Customer.FIND_BY_NAME", query = "SELECT c FROM Customer c WHERE c.name like :name") })
- public class Customer {
- @Id
- @Column(name = "id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private int id;
- @Column(name = "name")
- private String name;
- @Column(name = "address")
- private String address;
-
- // getter - setter
- }
package stackjava.com.hibernatenamedquery.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "customer")
@NamedQueries({
@NamedQuery(name = "Customer.FIND_ALL", query = "FROM Customer"),
@NamedQuery(name = "Customer.FIND_BY_NAME", query = "SELECT c FROM Customer c WHERE c.name like :name") })
public class Customer {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
// getter - setter
}
package stackjava.com.hibernatenamedquery.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "customer")
@NamedQueries({
@NamedQuery(name = "Customer.FIND_ALL", query = "FROM Customer"),
@NamedQuery(name = "Customer.FIND_BY_NAME", query = "SELECT c FROM Customer c WHERE c.name like :name") })
public class Customer {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
// getter - setter
}
Annotation @NameQueries được sử dụng để định nghĩa nhiều named query.
Annotation @NameQuery được sử dụng để định nghĩa một named query đơn.
Demo với Entitymanager
- DemoWithEntityManager.java
- package stackjava.com.hibernatenamedquery;
- import java.util.List;
- import javax.persistence.EntityManager;
- import javax.persistence.EntityManagerFactory;
- import javax.persistence.Persistence;
- import javax.persistence.Query;
- import stackjava.com.hibernatenamedquery.model.Customer;
- public class DemoWithEntityManager {
- public static void main(String[] args) {
- EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
- EntityManager entityManager = entityManagerFactory.createEntityManager();
- System.out.println("----------------- find all -----------------");
- Query queryFindAll = entityManager.createNamedQuery("Customer.FIND_ALL");
- List<Customer> listCustomer = queryFindAll.getResultList();
- listCustomer.forEach(c -> {
- System.out.println(c);
- });
- System.out.println("----------------- search by name 'th' -----------------");
- Query queryFindByName = entityManager.createNamedQuery("Customer.FIND_BY_NAME");
- queryFindByName.setParameter("name", "%th%");
- List<Customer> listCustomer2 = queryFindByName.getResultList();
- listCustomer2.forEach(c -> {
- System.out.println(c);
- });
- }
- }
package stackjava.com.hibernatenamedquery;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import stackjava.com.hibernatenamedquery.model.Customer;
public class DemoWithEntityManager {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
EntityManager entityManager = entityManagerFactory.createEntityManager();
System.out.println("----------------- find all -----------------");
Query queryFindAll = entityManager.createNamedQuery("Customer.FIND_ALL");
List<Customer> listCustomer = queryFindAll.getResultList();
listCustomer.forEach(c -> {
System.out.println(c);
});
System.out.println("----------------- search by name 'th' -----------------");
Query queryFindByName = entityManager.createNamedQuery("Customer.FIND_BY_NAME");
queryFindByName.setParameter("name", "%th%");
List<Customer> listCustomer2 = queryFindByName.getResultList();
listCustomer2.forEach(c -> {
System.out.println(c);
});
}
}
package stackjava.com.hibernatenamedquery;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import stackjava.com.hibernatenamedquery.model.Customer;
public class DemoWithEntityManager {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
EntityManager entityManager = entityManagerFactory.createEntityManager();
System.out.println("----------------- find all -----------------");
Query queryFindAll = entityManager.createNamedQuery("Customer.FIND_ALL");
List<Customer> listCustomer = queryFindAll.getResultList();
listCustomer.forEach(c -> {
System.out.println(c);
});
System.out.println("----------------- search by name 'th' -----------------");
Query queryFindByName = entityManager.createNamedQuery("Customer.FIND_BY_NAME");
queryFindByName.setParameter("name", "%th%");
List<Customer> listCustomer2 = queryFindByName.getResultList();
listCustomer2.forEach(c -> {
System.out.println(c);
});
}
}
Demo với Session
- package stackjava.com.hibernatenamedquery;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import stackjava.com.hibernatenamedquery.model.Customer;
- public class DemoWithSession {
- public static void main(String[] args) {
- SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
- Session session = sessionFactory.openSession();
- System.out.println("----------------- find all -----------------");
- Query queryFindAll = session.getNamedQuery("Customer.FIND_ALL");
- List<Customer> listCustomer = queryFindAll.list();
- listCustomer.forEach(c -> {
- System.out.println(c);
- });
- System.out.println("----------------- search by name 'th' -----------------");
- Query queryFindByName = session.getNamedQuery("Customer.FIND_BY_NAME");
- queryFindByName.setParameter("name", "%th%");
- List<Customer> listCustomer2 = queryFindByName.list();
- listCustomer2.forEach(c -> {
- System.out.println(c);
- });
-
- }
- }
package stackjava.com.hibernatenamedquery;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import stackjava.com.hibernatenamedquery.model.Customer;
public class DemoWithSession {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("----------------- find all -----------------");
Query queryFindAll = session.getNamedQuery("Customer.FIND_ALL");
List<Customer> listCustomer = queryFindAll.list();
listCustomer.forEach(c -> {
System.out.println(c);
});
System.out.println("----------------- search by name 'th' -----------------");
Query queryFindByName = session.getNamedQuery("Customer.FIND_BY_NAME");
queryFindByName.setParameter("name", "%th%");
List<Customer> listCustomer2 = queryFindByName.list();
listCustomer2.forEach(c -> {
System.out.println(c);
});
}
}
package stackjava.com.hibernatenamedquery;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import stackjava.com.hibernatenamedquery.model.Customer;
public class DemoWithSession {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("----------------- find all -----------------");
Query queryFindAll = session.getNamedQuery("Customer.FIND_ALL");
List<Customer> listCustomer = queryFindAll.list();
listCustomer.forEach(c -> {
System.out.println(c);
});
System.out.println("----------------- search by name 'th' -----------------");
Query queryFindByName = session.getNamedQuery("Customer.FIND_BY_NAME");
queryFindByName.setParameter("name", "%th%");
List<Customer> listCustomer2 = queryFindByName.list();
listCustomer2.forEach(c -> {
System.out.println(c);
});
}
}
Kết quả:
----------------- find all -----------------
Customer [id=1, name=Kai, address=Viet Nam]
Customer [id=2, name=Thanos, address=Titan]
Customer [id=3, name=Thor, address=Asgard]
Customer [id=4, name=Hulk, address=USA]
Customer [id=5, name=Iron Man, address=USA]
----------------- search by name 'th' -----------------
Customer [id=2, name=Thanos, address=Titan]
Customer [id=3, name=Thor, address=Asgard]
- ----------------- find all -----------------
- Customer [id=1, name=Kai, address=Viet Nam]
- Customer [id=2, name=Thanos, address=Titan]
- Customer [id=3, name=Thor, address=Asgard]
- Customer [id=4, name=Hulk, address=USA]
- Customer [id=5, name=Iron Man, address=USA]
- ----------------- search by name 'th' -----------------
- Customer [id=2, name=Thanos, address=Titan]
- Customer [id=3, name=Thor, address=Asgard]
----------------- find all -----------------
Customer [id=1, name=Kai, address=Viet Nam]
Customer [id=2, name=Thanos, address=Titan]
Customer [id=3, name=Thor, address=Asgard]
Customer [id=4, name=Hulk, address=USA]
Customer [id=5, name=Iron Man, address=USA]
----------------- search by name 'th' -----------------
Customer [id=2, name=Thanos, address=Titan]
Customer [id=3, name=Thor, address=Asgard]
Code ví dụ Hibernate Named Query (annotation @NamedQuery, @NameQueries) stackjava.com
Okay, Done!
Download code ví dụ trên tại đây.
References:
https://docs.jboss.org/…/NamedQuery.html
http://docs.jboss.org/hibernate/orm/5.2/…/annotations-jpa-namedquery