hibernate命名的查询是通过一些有意义的名称来使用查询的方式。就类似于使用别名一样。 Hibernate框架提供命名查询的概念,以便应用程序员不需要将查询分散到所有的java代码,进一步提高代码的可维护性。
在hibernate中定义命名查询有两种方法:
- 通过注释
- 通过映射文件
Hibernate通过注释命名查询
如果要在hibernate中使用命名查询,则需要了解@NamedQueries
和@NamedQuery
注释。
@NameQueries
注释用于定义多个命名查询。@NameQuery
注释用于定义单个命名查询。
我们来看看使用命名查询的例子:
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
Hibernate通过注释命名查询的示例
我们首先创建一个 Java 项目:namedquery
, 其完整的项目结构如下图所示 -
在这个例子中,我们使用注解来定义持久化类中的命名查询。只有三个文件:
- Employee.java
- hibernate.cfg.xml
- MainTest.java
在这个例子中,我们假设数据库中有一个em
表,其中包含4
列:id
,name
,job
和salary
,并且这个表中有一些记录。
文件:Employee.java
它是一个使用注释定义命名查询并将此类标记为实体的持久化类。
package com.yiibai;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
@Entity
@Table(name="em")
public class Employee {
int id;
String name;
int salary;
String job;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public String toString() {
return id + " " + name + " " + salary + " " + job;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
文件:hibernate.cfg.xml
它是一个配置文件,用于存储有关数据库的信息,如驱动程序类,URL,用户名,密码和映射类等。
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<mapping class="com.yiibai.Employee" />
</session-factory>
</hibernate-configuration>
文件:MainTest.java
它是一个使用命名查询的java类,并根据查询打印信息。getNamedQuery
方法使用命名查询并返回Query的实例。
package com.yiibai;
import java.util.Iterator;
import java.util.List;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.*;
public class MainTest {
public static void main(String[] args) {
// 在5.1.0版本汇总,hibernate则采用如下新方式获取:
// 1. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为final
// 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定资源路径,默认在类路径下寻找名为hibernate.cfg.xml的文件
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
// 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
SessionFactory sessionFactory = new MetadataSources(registry)
.buildMetadata().buildSessionFactory();
/**** 上面是配置准备,下面开始我们的数据库操作 ******/
Session session = sessionFactory.openSession();// 从会话工厂获取一个session
// creating transaction object
Transaction t = session.beginTransaction();
// 装点示例数据
Employee e1 = new Employee();
e1.setName("Maxsu");
e1.setJob("Java开发工程师");
e1.setSalary(8900);
session.save(e1);
Employee e2 = new Employee();
e2.setName("Minalee");
e2.setJob("Python开发工程师");
e2.setSalary(9500);
session.save(e2);
t.commit();
// Hibernate Named Query
Query query = session.getNamedQuery("findEmployeeByName");
query.setString("name", "Maxsu");
List<Employee> employees = query.list();
Iterator<Employee> itr = employees.iterator();
while (itr.hasNext()) {
Employee e = itr.next();
System.out.println(e);
}
session.close();
}
}
方法2. Hibernate通过XML映射文件命名查询
如果要通过映射文件定义命名查询,则需要使用hibernate-mapping
的query
元素来定义命名查询。
在这种情况下,需要创建定义命名查询的hbm
文件。 其他资源与上述示例中相同,除了持久化类Employee.java
,您不需要使用任何注释和hibernate.cfg.xml
文件,需要指定hbm
文件中的映射资源。
emp.hbm.xml
文件应该是这样的:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.yiibai.Employee" table="em">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="job"></property>
<property name="salary"></property>
</class>
<query name="findEmployeeByName">
<![CDATA[from Employee e where e.name = :name]]>
</query>
</hibernate-mapping>
持久化的类应该如下所示,文件:Employee.java -
package com.yiibai;
public class Employee {
int id;
String name;
int salary;
String job;
public String toString() {
return id + " " + name + " " + salary + " " + job;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
在hbm文件中包含映射资源。文件:hibernate.cfg.xml 如下所示 -
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<mapping resource="emp.hbm.xml" />
</session-factory>
</hibernate-configuration>
运行示例
现在运行 MainTest.java
文件,它首先创建表结构,并向表中插入数据,然后使用命名查询数据。得到结果如下所示-
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Tue Mar 28 23:08:07 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: create table em (id integer not null auto_increment, name varchar(255), job varchar(255), salary integer, primary key (id)) engine=InnoDB
Hibernate: insert into em (name, job, salary) values (?, ?, ?)
Hibernate: insert into em (name, job, salary) values (?, ?, ?)
Hibernate: select employee0_.id as id1_0_, employee0_.name as name2_0_, employee0_.job as job3_0_, employee0_.salary as salary4_0_ from em employee0_ where employee0_.name=?
1 Maxsu 8900 Java开发工程师