【JavaEE学习笔记】Hibernate_02_连接池,HQL

Hibernate_02

A.连接池

1.c3p0

a.导入Hibernate和mysql数据库的jar包


b.导入c3p0jar包


c.编写UserInfo.Java类

package org.xxxx.pojo;

import java.io.Serializable;

public class UserInfo implements Serializable {

	private static final long serialVersionUID = 1L;

	private int id;
	private String username;
	private String password;

	public UserInfo() {
		super();
		// TODO Auto-generated constructor stub
	}

	public UserInfo(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	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;
	}

	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", username=" + username + ", password=" + password + "]";
	}

}

d.编写配置文件

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="hibernaet.connection.deiver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<!-- mysql方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL57Dialect</property>
		<!-- 创建表方式为自动更新 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 是否显示sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 是否格式化 -->
		<property name="hibernate.format_sql">true</property>
		<!-- c3p0配置信息 配置连接池初始化大小 -->
		<property name="initialSize">2</property>
		<!-- 最小空闲连接数 -->
		<property name="minIdle">1</property>
		<!-- 最大连接数 -->
		<property name="maxActive">300</property>
		<!-- 获取连接等待超时的时间,单位:毫秒 -->
		<property name="maxWait">60000</property>
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis">60000</property>
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis">300000</property>

		<!-- 映射位置 -->
		<mapping resource="org/xxxx/pojo/UserInfo.hbm.xml" />

	</session-factory>
</hibernate-configuration>

UserInfo.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-1-13 20:10:19 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping package="org.xxxx.pojo">
    <class name="UserInfo" table="USERINFO">
        <id name="id" type="int">
            <column name="UID" />
            <!-- 自增长 -->
            <generator class="native" />
        </id>
        <property name="username" type="java.lang.String">
            <column name="USERNAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
    </class>
</hibernate-mapping>

e.测试类

编写测试类

package org.xxxx.pojo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test_01 {
	public static void main(String[] args) {
		// 加载配置文件
		Configuration config = new Configuration().configure();
		
		// 创建Session工厂
		SessionFactory factory = config.buildSessionFactory();
		
		// 获取Session
		Session session = factory.openSession();
		
		// 打开事物
		Transaction action = session.beginTransaction();
		
		// 创建对象
		UserInfo uInfo = new UserInfo("zhangsan", "123456");
		
		// 执行save
		session.save(uInfo);
		
		// 提交事物
		action.commit();
		
		// 释放资源
		session.close();
	}
}

运行,查看控制台


数据库


2.druid

a.导入Hibernate和mysql数据库的jar包(与c3p0相同)

b.导入druid驱动jar包


c.编写UserInfo(与c3p0相同)

d.编写配置文件(只需改动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="diverClassName">com.mysql.jdbc.Driver</property>
		<property name="url">jdbc:mysql://localhost:3306/test</property>
		<property name="username">root</property>
		<property name="password">root</property>

		<!-- 添加驱动 -->
		<property name="hibernate.connection.provider_class">com.alibaba.druid.support.hibernate.DruidConnectionProvider</property>

		<!-- mysql方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL57Dialect</property>
		<!-- 创建表方式为自动更新 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 是否显示sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 是否格式化 -->
		<property name="hibernate.format_sql">true</property>

		<!-- 配置连接池初始化大小 -->
		<property name="initialSize">2</property>
		<!-- 最小空闲连接数 -->
		<property name="minIdle">1</property>
		<!-- 最大连接数 -->
		<property name="maxActive">300</property>
		<!-- 获取连接等待超时的时间,单位:毫秒 -->
		<property name="maxWait">60000</property>
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis">60000</property>
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis">300000</property>

		<!-- 映射位置 -->
		<mapping resource="org/xxxx/pojo/UserInfo.hbm.xml" />

	</session-factory>
</hibernate-configuration>

e.编写测试类(与c3p0相同,只需改动输入数据即可)

运行查看结果


3.总结

c3p0是hibernate官方内置的,因此使用时只需要导入jar包并配置参数即可

druid是阿里巴巴推出的,速度更快,在配置文件里需要配置很多信息

B.HQL查询语言(除了测试类,其他的代码都跟上面的一样)

1.HQL

Hibernate Query Language,被设计为完全面向对象的查询语言

可以使用绝大多数SQL函数,并提供一些HQL函数

它主要是针对持久化对象进行查询

可以执行update,delete,insert等操作

SQL的操作对象是数据库,列等数据库对象

而HQL的操作对象是类,实例,属性等

HQL不支持Insert,不是别values

2.语法

[select] from 类名列表 [where 子句] [group by 子句] [order by 子句]

select跟的是需要返回的对象或者对象属性

且属性必须属于from子句中给出的类列表

3.查询具体属性(单个属性的查询)

语法:select colunm_name from table_name where condition

Query<T> createQuery(hql);执行语句

List<T> getResultList();返回结果集

package org.xxxx.pojo;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class Test_01 {
	public static void main(String[] args) {
		// 加载配置文件
		Configuration config = new Configuration().configure();

		// 创建Session工厂
		SessionFactory factory = config.buildSessionFactory();

		// 获取Session
		Session session = factory.openSession();

		// 定义hql语句
		String hql = "select username from UserInfo where id=2";

		// 执行语句
		@SuppressWarnings("unchecked")
		Query<String> query = session.createQuery(hql);

		// 获取结果
		List<String> list = query.getResultList();

		// 遍历输出
		for (String username : list) {
			System.out.println(username);
		}

		// 释放资源
		session.close();
	}
}

4.查询其中几列数据

select column_01,column_02 from table_name where condition;

		// 定义hql语句
		String hql = "select username,password from UserInfo where id=2";

		// 执行语句
		@SuppressWarnings("unchecked")
		Query<Object> query = session.createQuery(hql);

		// 获取结果
		List<Object> list = query.getResultList();

		// 遍历
		for (Object obj : list) {
			// obj是个数组
			Object[] objs = (Object[]) obj;
			System.out.println(objs[0] + "---" + objs[1]);
		}

5.查询并生成对象

select new UserInfo(username,password) from UserInfo where condition

Object uniqueResult();获取结果并生成对象

		// 定义hql语句
		String hql = "select new UserInfo(username,password) from UserInfo where id=1";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 获取结果
		UserInfo uInfo = query.uniqueResult();
		System.out.println(uInfo);

6.查询所有属性:不能使用*

from table_name

		// 定义hql语句
		String hql = "from UserInfo";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 获取结果
		List<UserInfo> list = query.getResultList();
		
		for (UserInfo uInfo : list) {
			System.out.println(uInfo);
		}

7.使用占位符?,索引从0开始

		// 定义hql语句
		String hql = "from UserInfo where id=?";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 设置参数
		query.setParameter(0, 2);
		
		// 获取结果
		UserInfo uInfo = query.uniqueResult();
		System.out.println(uInfo);

8.使用命名参数,在参数前面需要加上冒号

		// 定义hql语句
		String hql = "from UserInfo where id=:id and username=:username";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 设置参数
		query.setParameter("username", "zhangsan");
		query.setParameter("id", 1);
		
		// 获取结果
		UserInfo uInfo = query.uniqueResult();
		System.out.println(uInfo);

9.使用集合或数组参数

		// list集合传参
		List<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(2);
		
		// 定义hql语句
		String hql = "from UserInfo where id in(:ids)";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 设置参数
		query.setParameter("ids", list);
		
		// 获取结果
		List<UserInfo> list2 = query.getResultList();
		for (UserInfo uInfo : list2) {
			System.out.println(uInfo);
		}

10.范围查询

再添加几组数据


查询id在2到4之间的信息

		// 定义hql语句
		String hql = "from UserInfo where id between 2 and 4";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 获取数据
		List<UserInfo> list = query.getResultList();
		
		// 遍历
		for (UserInfo uInfo : list) {
			System.out.println(uInfo);
		}

11.模糊查询

%不能写在HQL上,要写到参数上

查询名字以i结尾的信息

		// 定义hql语句
		String hql = "from UserInfo where username like ?";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 设置参数
		query.setParameter(0, "%i");
		
		// 获取数据
		List<UserInfo> list = query.getResultList();
		
		for (UserInfo uInfo : list) {
			System.out.println(uInfo);
		}

12.聚合函数统计

count(),统计

统计一共有多少条信息

		// 定义hql语句
		String hql = "select count(id) from UserInfo";
		
		// 执行
		@SuppressWarnings("unchecked")
		Query<Long> query = session.createQuery(hql);
		
		// 获取数据
		Long count = query.uniqueResult();
		
		System.out.println(count);

13.分组查询

按姓名分组

		// 定义hql语句
		String hql = "select username,count(username) from UserInfo group by username";

		// 执行
		@SuppressWarnings("unchecked")
		Query<Object> query = session.createQuery(hql);

		// 获取数据
		List<Object> list = query.getResultList();

		for (Object obj : list) {
			Object[] o = (Object[]) obj;
			System.out.println(o[0] + "---" + o[1]);
		}

14.WHER、GROUP BY、HAVING和ORDER综合

查询id大于1,数量大于1的人名和人数

		// 定义hql语句
		String hql = "select username,count(username) from UserInfo where id>1 group by username having count(username)>1";

		// 执行
		@SuppressWarnings("unchecked")
		Query<Object> query = session.createQuery(hql);

		// 获取数据
		List<Object> list = query.getResultList();

		for (Object obj : list) {
			Object[] o = (Object[]) obj;
			System.out.println(o[0] + "---" + o[1]);
		}

15.更新

int createQuery(hql).executeUpdate();

		// 开启事物
		Transaction transaction = session.beginTransaction();
		
		// 定义hql语句
		String hql = "update UserInfo set username='chengliu' where id=5";

		// 执行
		int i = session.createQuery(hql).executeUpdate();
		System.out.println(i);
		
		// 提交事物
		transaction.commit();

数据库


16.删除

delete User where id=?

		// 开启事物
		Transaction transaction = session.beginTransaction();
		
		// 定义hql语句
		String hql = "delete UserInfo where id=5";

		// 执行
		int i = session.createQuery(hql).executeUpdate();
		System.out.println(i);
		
		// 提交事物
		transaction.commit();

17.分页

setFirstResult();//开始位置 =(页数 - 1) * 条数

setMaxResult();//记录条数

		// 定义hql语句
		String hql = "from UserInfo";

		// 执行
		@SuppressWarnings("unchecked")
		Query<UserInfo> query = session.createQuery(hql);
		
		// 设置分页参数
		query.setFirstResult(2);
		query.setMaxResults(2);
		
		// 获取结果
		List<UserInfo> list = query.getResultList();

		for (UserInfo uInfo : list) {
			System.err.println(uInfo);
		}

猜你喜欢

转载自blog.csdn.net/wpf719971425/article/details/79053327