hibernate查询接口Query用法

本文介绍了如何利用Hibernate的Query接口进行复杂查询操作。通过Session创建Query对象,并使用hql语句配合setParameter方法实现动态参数传入。Query接口的list方法用于获取查询结果列表,uniqResult用于获取唯一记录,而executeUpdate则用于执行更新或删除操作。以hibernate-core-4.3.10.Final版本为示例,实体映射采用Hibernate注解,并展示了项目的构建配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hibernate的Session接口提供了get,load等按照id查询单个记录的方法,但是大多数时候,我们查询的是实体类的集合列表,这就需要用到复杂查询了,hibernate提供了类sql语句hql,他可以帮助我们编写复杂的查询语句,来做复杂的增删改查操作。这里介绍hibernate提供的Query接口用法。

Query接口的创建是通过Session来创建的,默认需要传入一个hql语句,比如sess.createQuery(hql)。如果我们需要在hql语句中传入参数,可以调用query.setParameter()等方法,可以做到动态传参。

另外Query提供的list,uniqResult,executeUpdate等方法,他们分别对应如下:

list:查询列表
uniqResult:查询唯一记录
executeUpdate:执行修改或者删除操作
这里以hibernate-core-4.3.10.Final版本为例,为了简单,实体映射采用hibernate注解来实现,构建maven工程:

pom.xml
 

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.10.Final</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
</dependency>

BaseEntity.java

package com.xxx.hibernate4.entity;
 
import java.io.Serializable;
import java.util.Date;
 
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class BaseEntity implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	protected Integer id;
	@Column(name="createdate")
	protected Date createDate;
	@Column(name="modifydate")
	protected Date modifyDate;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	
}

User.java

package com.xxx.hibernate4.entity;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="xx_user")
public class User extends BaseEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	@Column(length=11)
	private String mobile;
	private int age;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + 
               ", mobile=" + mobile + ", age=" + age + ", id="
				+ id + "]";
	}
	
	
}

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
  <session-factory>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql:///hibernate4?useUnicode=true&amp;useSSL=false&amp;characterEncoding=UTF-8</property>
      <property name="connection.username">hadoop</property>
      <property name="connection.password">hadoop</property>
      <property name="connection.pool_size">1</property>
      <property name="dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="hbm2ddl.auto">update</property>
      <mapping class="com.xxx.hibernate4.entity.User"/>
  </session-factory>
</hibernate-configuration>

代码:

package com.xxx.hibernate4;
import java.util.List;
 
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
import com.xxx.hibernate4.entity.User;
@SuppressWarnings("deprecation")
public class SearchByHQL {
 
	public static SessionFactory sessionFactory;
	public static final ThreadLocal<Session> session = new ThreadLocal<>();
	static {
		try {
			Configuration cfg = new Configuration().configure();
			sessionFactory = cfg.buildSessionFactory();
		} catch (HibernateException e) {
			e.printStackTrace();
			System.err.println("Initialize SessionFactory fail "+e);
		}
	}
	
	public static Session getSession() {
		Session sess = (Session)session.get();
		if(sess==null) {
			sess = sessionFactory.openSession();
			session.set(sess);
		}
		return sess;
	}
	
	public static void closeSession() {
		Session sess = (Session)session.get();
		if(sess!=null) {
			sess.close();
		}
		session.set(null);
		sessionFactory.close();
	}
	
	@SuppressWarnings("unchecked")
	public static void searchByHQL() {
		Session sess = getSession();
		String hql = "from User";
		Query query = sess.createQuery(hql);
		List<User> list = query.list();
		for(User user:list) {
			System.out.println(user);
		}
		closeSession();
	}
	
	public static void main(String[] args) {
		searchByHQL();
	}
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值