本文主要是介绍hibernate进二阶之各式查询,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
hibernate.cfg.xml
<!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节点代表一个数据库 --><session-factory><!-- 1. 数据库连接配置 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hib04</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><!-- 数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql--><property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- 2. 其他相关配置 --><!-- 2.1 显示hibernate在运行时候执行的sql语句 --><property name="hibernate.show_sql">true</property><!-- 2.2 格式化sql<property name="hibernate.format_sql">true</property> --><!-- 2.3 自动建表 --><property name="hibernate.hbm2ddl.auto">update</property><!-- 配置session的创建方式:线程方式创建session对象 --><property name="hibernate.current_session_context_class">thread</property><!--****************** 【连接池配置】****************** --><!-- 配置连接驱动管理类 --><property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property><!-- 配置连接池参数信息 --><property name="hibernate.c3p0.min_size">2</property><property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">5000</property><property name="hibernate.c3p0.max_statements">10</property><property name="hibernate.c3p0.idle_test_period">30000</property><property name="hibernate.c3p0.acquire_increment">2</property></session-factory>
</hibernate-configuration>
Dept.java
package cn.itcast.a_query;import java.util.HashSet;
import java.util.Set;public class Dept {private int deptId;private String deptName;// 【一对多】 部门对应的多个员工private Set<Employee> emps = new HashSet<Employee>();public Dept(int deptId, String deptName) {super();this.deptId = deptId;this.deptName = deptName;}public Dept() {super();}public int getDeptId() {return deptId;}public void setDeptId(int deptId) {this.deptId = deptId;}public String getDeptName() {return deptName;}public void setDeptName(String deptName) {this.deptName = deptName;}public Set<Employee> getEmps() {return emps;}public void setEmps(Set<Employee> emps) {this.emps = emps;}
}
Employee.java
package cn.itcast.a_query;public class Employee {private int empId;private String empName;private double salary;// 【多对一】员工与部门private Dept dept;;public int getEmpId() {return empId;}public void setEmpId(int empId) {this.empId = empId;}public String getEmpName() {return empName;}public void setEmpName(String empName) {this.empName = empName;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public Dept getDept() {return dept;}public void setDept(Dept dept) {this.dept = dept;}
}
Dept.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.itcast.a_query"><class name="Dept" table="t_dept" ><id name="deptId"><generator class="native"></generator></id> <property name="deptName" length="20"></property><set name="emps"><key column="dept_id"></key><one-to-many class="Employee"/></set></class><!-- 存放sql语句 --><query name="getAllDept"><!-- 用于转义 --><![CDATA[from Dept d where deptId < ?]]></query>
</hibernate-mapping>
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.itcast.a_query"><class name="Employee" table="t_employee"><id name="empId"><generator class="native"></generator></id> <property name="empName" length="20"></property><property name="salary" type="double"></property><many-to-one name="dept" column="dept_id" class="Dept"></many-to-one> </class>
</hibernate-mapping>
分页查询:注意获得总记录数的滚动结果集方法
public class App_page {private static SessionFactory sf;static {sf = new Configuration().configure().addClass(Dept.class) .addClass(Employee.class) // 测试时候使用.buildSessionFactory();}// 分页查询@Testpublic void all() {Session session = sf.openSession();session.beginTransaction();Query q = session.createQuery("from Employee");// 从记录数ScrollableResults scroll = q.scroll(); // 得到滚动的结果集scroll.last(); // 滚动到最后一行int totalCount = scroll.getRowNumber() + 1;// 得到滚到的记录数,即总记录数// 设置分页参数q.setFirstResult(0);q.setMaxResults(3);// 查询System.out.println(q.list());System.out.println("总记录数:" + totalCount);session.getTransaction().commit();session.close();}
}
App_hql.java--各式查询汇总
public class App_hql {private static SessionFactory sf;static {sf = new Configuration().configure().addClass(Dept.class) .addClass(Employee.class) // 测试时候使用.buildSessionFactory();}/** 1) Get/load主键查询2) 对象导航查询3) HQL查询, Hibernate Query language hibernate 提供的面向对象的查询语言。4) Criteria 查询, 完全面向对象的查询(Query By Criteria ,QBC)5) SQLQuery, 本地SQL查询*/@Testpublic void all() {Session session = sf.openSession();session.beginTransaction();//1) 主键查询
// Dept dept = (Dept) session.get(Dept.class, 12);
// Dept dept = (Dept) session.load(Dept.class, 12);//2) 对象导航查询
// Dept dept = (Dept) session.get(Dept.class, 12);
// System.out.println(dept.getDeptName());
// System.out.println(dept.getEmps());// 3) HQL查询// 注意:使用hql查询的时候 auto-import="true" 要设置true,// 如果是false,写hql的时候,要指定类的全名
// Query q = session.createQuery("from Dept");
// System.out.println(q.list());// a. 查询全部列
// Query q = session.createQuery("from Dept"); //OK
// Query q = session.createQuery("select * from Dept"); //NOK, 错误,不支持*
// Query q = session.createQuery("select d from Dept d"); // OK
// System.out.println(q.list());// b. 查询指定的列 【返回对象数据Object[] 】,查询到的每个元素是Object[]//如果只是查询一列,返回 指定类型的列数据
// Query q = session.createQuery("select d.deptId,d.deptName from Dept d");
// System.out.println(q.list());// c. 查询指定的列, 自动封装为对象 【必须要提供带参数构造器】
// Query q = session.createQuery("select new Dept(d.deptId,d.deptName) from Dept d");
// System.out.println(q.list()); // d. 条件查询: 一个条件/多个条件and or/between and/模糊查询// 条件查询: 占位符【记得从0开始】
// Query q = session.createQuery("from Dept d where deptName=?");
// q.setString(0, "财务部");
// q.setParameter(0, "财务部");
// System.out.println(q.list());// 条件查询: ★命名参数★,不要加空格
// Query q = session.createQuery("from Dept d where deptId=:myId or deptName=:name");
// q.setParameter("myId", 12);
// q.setParameter("name", "财务部");
// System.out.println(q.list());// 范围
// Query q = session.createQuery("from Dept d where deptId between ? and ?");
// q.setParameter(0, 1);
// q.setParameter(1, 20);
// System.out.println(q.list());// 模糊
// Query q = session.createQuery("from Dept d where deptName like ?");
// q.setString(0, "%部%");
// System.out.println(q.list());// e. 聚合函数统计//[select count(deptname) from t_dept 会忽略null值,这是和count(*),count(1)的区别,亲测为然]//[hibernate 只支持count(*)]
// Query q = session.createQuery("select count(*) from Dept");
// Long num = (Long) q.uniqueResult();
// System.out.println(num);// f. 分组查询//-- 统计t_employee表中,每个部门的人数//数据库写法:SELECT COUNT(*) FROM t_employee GROUP BY dept_id;//分组后的条件后面依然加的having count(*) > 4// HQL写法
// Query q = session.createQuery("select e.dept, count(*) from Employee e group by e.dept");
// System.out.println(q.list());session.getTransaction().commit();session.close();}// g. 连接查询@Testpublic void join() {Session session = sf.openSession();session.beginTransaction();//1) 内连接 【映射已经配置好了关系,关联的时候,直接写对象的属性即可】
// Query q = session.createQuery("from Dept d inner join d.emps");//2) 左外连接
// Query q = session.createQuery("from Dept d left join d.emps");//3) 右外连接Query q = session.createQuery("from Employee e right join e.dept");q.list();session.getTransaction().commit();session.close();}// g. 连接查询 - 迫切连接@Testpublic void fetch() {Session session = sf.openSession();session.beginTransaction();//1) 迫切内连接 【使用fetch, 会把右表的数据,填充到左表对象中!】
// Query q = session.createQuery("from Dept d inner join fetch d.emps");
// q.list();//2) 迫切左外连接Query q = session.createQuery("from Dept d left join fetch d.emps");q.list();session.getTransaction().commit();session.close();}// HQL查询优化@Testpublic void hql_other() {Session session = sf.openSession();session.beginTransaction();// HQL写死
// Query q = session.createQuery("from Dept d where deptId < 10 ");// HQL 放到映射文件中Query q = session.getNamedQuery("getAllDept");q.setParameter(0, 10);System.out.println(q.list());session.getTransaction().commit();session.close();}
}
这篇关于hibernate进二阶之各式查询的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!