码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate的学习详解(4)

时间:2015-09-16 15:50:16      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

         HQL的学习:

 

          hql语句对应的是实体表中的字段.

                from User  u where u.id= 1

 

 1 <hibernate-mapping>
 2 
 3     <class name="com.atguigu.hibernate.entities.Employee" table="GG_EMPLOYEE">
 4         
 5         <!--  
 6         <cache usage="read-write"/>
 7         -->
 8             
 9         <id name="id" type="java.lang.Integer">
10             <column name="ID" />
11             <generator class="native" />
12         </id>
13     
14         <property name="name" type="java.lang.String">
15             <column name="NAME" />
16         </property>
17         
18         <property name="salary" type="float">
19             <column name="SALARY" />
20         </property>
21         
22         <property name="email" type="java.lang.String">
23             <column name="EMAIL" />
24         </property>
25         
26         <many-to-one name="dept" class="com.atguigu.hibernate.entities.Department">
27             <column name="DEPT_ID" />
28         </many-to-one>
29         
30     </class>
31     
32     <query name="salaryEmps"><![CDATA[FROM Employee e WHERE e.salary > :minSal AND e.salary < :maxSal]]></query>
33     
34 </hibernate-mapping>

      

•分页查询:
–setFirstResult(int firstResult): 设定从哪一个对象开始检索, 参数 firstResult 表示这个对象在查询结果中的索引位置, 索引位置的起始值为 0. 默认情况下, Query 从查询结果中的第一个对象开始检索
–setMaxResults(int maxResults): 设定一次最多检索出的对象的数目. 在默认情况下, Query 和 Criteria 接口检索出查询结果中所有的对象

     

  

•投影查询: 查询结果仅包含实体的部分属性. 通过 SELECT 关键字实现.

 

•Query 的 list() 方法返回的集合中包含的是数组类型的元素, 每个对象数组代表查询结果的一条记录

 

•可以在持久化类中定义一个对象的构造器来包装投影查询返回的记录, 使程序代码能完全运用面向对象的语义来访问查询结果集.

 

•可以通过 DISTINCT 关键字来保证查询结果不会返回重复元素
 
•报表查询用于对数据分组和统计, 与 SQL 一样, HQL 利用 GROUP BY 关键字对数据分组, 用 HAVING 关键字对分组数据设定约束条件.
•在 HQL 查询语句中可以调用以下聚集函数
–count()
–min()
–max()
–sum()
avg()
 
 
  1 @Test
  2     public void testLeftJoinFetch(){
  3 //        String hql = "SELECT DISTINCT d FROM Department d LEFT JOIN FETCH d.emps";
  4         String hql = "FROM Department d INNER JOIN FETCH d.emps";
  5         Query query = session.createQuery(hql);
  6         
  7         List<Department> depts = query.list();
  8         depts = new ArrayList<>(new LinkedHashSet(depts));
  9         System.out.println(depts.size()); 
 10         
 11         for(Department dept: depts){
 12             System.out.println(dept.getName() + "-" + dept.getEmps().size());
 13         }
 14     }
 15     
 16     @Test
 17     public void testGroupBy(){
 18         String hql = "SELECT min(e.salary), max(e.salary) "
 19                 + "FROM Employee e "
 20                 + "GROUP BY e.dept "
 21                 + "HAVING min(salary) > :minSal";
 22         
 23         Query query = session.createQuery(hql)
 24                              .setFloat("minSal", 8000);
 25         
 26         List<Object []> result = query.list();
 27         for(Object [] objs: result){
 28             System.out.println(Arrays.asList(objs));
 29         }
 30     }
 31     //构造函数用投影查询
 32     @Test
 33     public void testFieldQuery2(){
 34         String hql = "SELECT new Employee(e.email, e.salary, e.dept) "
 35                 + "FROM Employee e "
 36                 + "WHERE e.dept = :dept";
 37         Query query = session.createQuery(hql);
 38         
 39         Department dept = new Department();
 40         dept.setId(80);
 41         List<Employee> result = query.setEntity("dept", dept)
 42                                      .list();
 43         
 44         for(Employee emp: result){
 45             System.out.println(emp.getId() + ", " + emp.getEmail() 
 46                     + ", " + emp.getSalary() + ", " + emp.getDept());
 47         }
 48     }
 49     //投影查询
 50     @Test
 51     public void testFieldQuery(){
 52         String hql = "SELECT e.email, e.salary, e.dept FROM Employee e WHERE e.dept = :dept";
 53         Query query = session.createQuery(hql);
 54         
 55         Department dept = new Department();
 56         dept.setId(80);
 57         List<Object[]> result = query.setEntity("dept", dept)
 58                                      .list();
 59         
 60         for(Object [] objs: result){
 61             System.out.println(Arrays.asList(objs));
 62         }
 63     }
 64     
 65     @Test
 66     public void testNamedQuery(){
 67         Query query = session.getNamedQuery("salaryEmps");
 68         
 69         List<Employee> emps = query.setFloat("minSal", 5000)
 70                                    .setFloat("maxSal", 10000)
 71                                    .list();
 72         
 73         System.out.println(emps.size()); 
 74     }
 75     //分页
 76     @Test
 77     public void testPageQuery(){
 78         String hql = "FROM Employee";
 79         Query query = session.createQuery(hql);
 80         
 81         int pageNo = 22;
 82         int pageSize = 5;
 83         
 84         List<Employee> emps = 
 85                                 query.setFirstResult((pageNo - 1) * pageSize)
 86                                      .setMaxResults(pageSize)
 87                                      .list();
 88         System.out.println(emps);
 89     }
 90     
 91     @Test
 92     public void testHQLNamedParameter(){
 93         
 94         //1. 创建 Query 对象
 95         //基于命名参数. 
 96         String hql = "FROM Employee e WHERE e.salary > :sal AND e.email LIKE :email";
 97         Query query = session.createQuery(hql);
 98         
 99         //2. 绑定参数
100         query.setFloat("sal", 7000)
101              .setString("email", "%A%");
102         
103         //3. 执行查询
104         List<Employee> emps = query.list();
105         System.out.println(emps.size());  
106     }
107     
108     @Test
109     public void testHQL(){
110         
111         //1. 创建 Query 对象
112         //基于位置的参数. 
113         String hql = "FROM Employee e WHERE e.salary > ? AND e.email LIKE ? AND e.dept = ? "
114                 + "ORDER BY e.salary";
115         Query query = session.createQuery(hql);
116         
117         //2. 绑定参数
118         //Query 对象调用 setXxx 方法支持方法链的编程风格.
119         Department dept = new Department();
120         dept.setId(80); 
121         query.setFloat(0, 6000)
122              .setString(1, "%A%")
123              .setEntity(2, dept);
124         
125         //3. 执行查询
126         List<Employee> emps = query.list();
127         System.out.println(emps.size());  
128     }

 

  技术分享

 

一般用迫切左外链接。

 

 

                                                                            hibernate的二级缓存

 

 

 1 <hibernate-configuration>
 2     <session-factory>
 3     
 4         <!-- Hibernate 连接数据库的基本信息 -->
 5         <property name="connection.username">scott</property>
 6         <property name="connection.password">java</property>
 7         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 8         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
 9 
10         <!-- Hibernate 的基本配置 -->
11         <!-- Hibernate 使用的数据库方言 -->
12         <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
13     
14         <!-- 运行时是否打印 SQL -->
15         <property name="show_sql">true</property>
16     
17         <!-- 运行时是否格式化 SQL -->
18         <property name="format_sql">true</property>
19     
20         <!-- 生成数据表的策略 -->
21         <property name="hbm2ddl.auto">update</property>
22         
23         <!-- 设置 Hibernate 的事务隔离级别 -->
24         <property name="connection.isolation">2</property>
25         
26         <!-- 删除对象后, 使其 OID 置为 null -->
27         <property name="use_identifier_rollback">true</property>
28         
29         <!-- 配置 C3P0 数据源 -->
30         <!--  
31         <property name="hibernate.c3p0.max_size">10</property>
32         <property name="hibernate.c3p0.min_size">5</property>
33         <property name="c3p0.acquire_increment">2</property>
34         
35         <property name="c3p0.idle_test_period">2000</property>
36         <property name="c3p0.timeout">2000</property>
37         
38         <property name="c3p0.max_statements">10</property>
39         -->
40         
41         <!-- 设定 JDBC 的 Statement 读取数据的时候每次从数据库中取出的记录条数 -->
42         <property name="hibernate.jdbc.fetch_size">100</property>
43         
44         <!-- 设定对数据库进行批量删除,批量更新和批量插入的时候的批次大小 -->
45         <property name="jdbc.batch_size">30</property>
46         
47         <!-- 启用二级缓存 -->
48         <property name="cache.use_second_level_cache">true</property>
49         
50         <!-- 配置使用的二级缓存的产品 -->
51         <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
52         
53         <!-- 配置启用查询缓存 -->
54         <property name="cache.use_query_cache">true</property>
55         
56         <!-- 配置管理 Session 的方式 -->
57         <property name="current_session_context_class">thread</property>
58         
59         <!-- 需要关联的 hibernate 映射文件 .hbm.xml -->
60         <mapping resource="com/atguigu/hibernate/entities/Department.hbm.xml"/>
61         <mapping resource="com/atguigu/hibernate/entities/Employee.hbm.xml"/>
62         
63         <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>
64         <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Department"/>
65         <collection-cache usage="read-write" collection="com.atguigu.hibernate.entities.Department.emps"/>
66     </session-factory>
67 </hibernate-configuration>

 

 

 

      

  1     @Test
  2     public void testBatch(){
  3         session.doWork(new Work() {            
  4             @Override
  5             public void execute(Connection connection) throws SQLException {
  6                 //通过 JDBC 原生的 API 进行操作, 效率最高, 速度最快!
  7             }
  8         });
  9     }
 10     
 11     @Test
 12     public void testManageSession(){
 13         
 14         //获取 Session
 15         //开启事务
 16         Session session = HibernateUtils.getInstance().getSession();
 17         System.out.println("-->" + session.hashCode());
 18         Transaction transaction = session.beginTransaction();
 19         
 20         DepartmentDao departmentDao = new DepartmentDao();
 21         
 22         Department dept = new Department();
 23         dept.setName("ATGUIGU");
 24         
 25         departmentDao.save(dept);
 26         departmentDao.save(dept);
 27         departmentDao.save(dept);
 28         
 29         //若 Session 是由 thread 来管理的, 则在提交或回滚事务时, 已经关闭 Session 了. 
 30         transaction.commit();
 31         System.out.println(session.isOpen()); 
 32     }
 33     
 34     @Test
 35     public void testQueryIterate(){
 36         Department dept = (Department) session.get(Department.class, 70);
 37         System.out.println(dept.getName());
 38         System.out.println(dept.getEmps().size()); 
 39         
 40         Query query = session.createQuery("FROM Employee e WHERE e.dept.id = 80");
 41 //        List<Employee> emps = query.list();
 42 //        System.out.println(emps.size()); 
 43         
 44         Iterator<Employee> empIt = query.iterate();
 45         while(empIt.hasNext()){
 46             System.out.println(empIt.next().getName()); 
 47         }
 48     }
 49     
 50     @Test
 51     public void testUpdateTimeStampCache(){
 52         Query query = session.createQuery("FROM Employee");
 53         query.setCacheable(true);
 54         
 55         List<Employee> emps = query.list();
 56         System.out.println(emps.size());
 57         
 58         Employee employee = (Employee) session.get(Employee.class, 100);
 59         employee.setSalary(30000);
 60         
 61         emps = query.list();
 62         System.out.println(emps.size());
 63     }
 64     
 65     @Test
 66     public void testQueryCache(){
 67         Query query = session.createQuery("FROM Employee");
 68         query.setCacheable(true);
 69         
 70         List<Employee> emps = query.list();
 71         System.out.println(emps.size());
 72         
 73         emps = query.list();
 74         System.out.println(emps.size());
 75         
 76         Criteria criteria = session.createCriteria(Employee.class);
 77         criteria.setCacheable(true);
 78     }
 79     
 80     @Test
 81     public void testCollectionSecondLevelCache(){
 82         Department dept = (Department) session.get(Department.class, 80);
 83         System.out.println(dept.getName());
 84         System.out.println(dept.getEmps().size()); 
 85         
 86         transaction.commit();
 87         session.close();
 88         
 89         session = sessionFactory.openSession();
 90         transaction = session.beginTransaction();
 91         
 92         Department dept2 = (Department) session.get(Department.class, 80);
 93         System.out.println(dept2.getName());
 94         System.out.println(dept2.getEmps().size()); 
 95     }
 96     
 97     @Test
 98     public void testHibernateSecondLevelCache(){
 99         Employee employee = (Employee) session.get(Employee.class, 100);
100         System.out.println(employee.getName()); 
101         
102         transaction.commit();
103         session.close();
104         
105         session = sessionFactory.openSession();
106         transaction = session.beginTransaction();
107         
108         Employee employee2 = (Employee) session.get(Employee.class, 100);
109         System.out.println(employee2.getName()); 
110     }
111     
112     @Test
113     public void testHQLUpdate(){
114         String hql = "DELETE FROM Department d WHERE d.id = :id";
115         
116         session.createQuery(hql).setInteger("id", 280)
117                                 .executeUpdate();
118     }
119     
120     @Test
121     public void testNativeSQL(){
122         String sql = "INSERT INTO gg_department VALUES(?, ?)";
123         Query query = session.createSQLQuery(sql);
124         
125         query.setInteger(0, 280)
126              .setString(1, "ATGUIGU")
127              .executeUpdate();
128     }
129     
130     @Test
131     public void testQBC4(){
132         Criteria criteria = session.createCriteria(Employee.class);
133         
134         //1. 添加排序
135         criteria.addOrder(Order.asc("salary"));
136         criteria.addOrder(Order.desc("email"));
137         
138         //2. 添加翻页方法
139         int pageSize = 5;
140         int pageNo = 3;
141         criteria.setFirstResult((pageNo - 1) * pageSize)
142                 .setMaxResults(pageSize)
143                 .list();
144     }
145     
146     @Test
147     public void testQBC3(){
148         Criteria criteria = session.createCriteria(Employee.class);
149         
150         //统计查询: 使用 Projection 来表示: 可以由 Projections 的静态方法得到
151         criteria.setProjection(Projections.max("salary"));
152         
153         System.out.println(criteria.uniqueResult()); 
154     }
155     
156     @Test
157     public void testQBC2(){
158         Criteria criteria = session.createCriteria(Employee.class);
159         
160         //1. AND: 使用 Conjunction 表示
161         //Conjunction 本身就是一个 Criterion 对象
162         //且其中还可以添加 Criterion 对象
163         Conjunction conjunction = Restrictions.conjunction();
164         conjunction.add(Restrictions.like("name", "a", MatchMode.ANYWHERE));
165         Department dept = new Department();
166         dept.setId(80);
167         conjunction.add(Restrictions.eq("dept", dept));
168         System.out.println(conjunction); 
169         
170         //2. OR
171         Disjunction disjunction = Restrictions.disjunction();
172         disjunction.add(Restrictions.ge("salary", 6000F));
173         disjunction.add(Restrictions.isNull("email"));
174         
175         criteria.add(disjunction);
176         criteria.add(conjunction);
177         
178         criteria.list();
179     }
180     
181     @Test
182     public void testQBC(){
183         //1. 创建一个 Criteria 对象
184         Criteria criteria = session.createCriteria(Employee.class);
185         
186         //2. 添加查询条件: 在 QBC 中查询条件使用 Criterion 来表示
187         //Criterion 可以通过 Restrictions 的静态方法得到
188         criteria.add(Restrictions.eq("email", "SKUMAR"));
189         criteria.add(Restrictions.gt("salary", 5000F));
190         
191         //3. 执行查询
192         Employee employee = (Employee) criteria.uniqueResult();
193         System.out.println(employee); 
194     }
195     
196     @Test
197     public void testLeftJoinFetch2(){
198         String hql = "SELECT e FROM Employee e INNER JOIN e.dept";
199         Query query = session.createQuery(hql);
200         
201         List<Employee> emps = query.list();
202         System.out.println(emps.size()); 
203         
204         for(Employee emp: emps){
205             System.out.println(emp.getName() + ", " + emp.getDept().getName());
206         }
207     }
208     
209     @Test
210     public void testLeftJoin(){
211         String hql = "SELECT DISTINCT d FROM Department d LEFT JOIN d.emps";
212         Query query = session.createQuery(hql);
213         
214         List<Department> depts = query.list();
215         System.out.println(depts.size());
216         
217         for(Department dept: depts){
218             System.out.println(dept.getName() + ", " + dept.getEmps().size()); 
219         }
220         
221 //        List<Object []> result = query.list(); 
222 //        result = new ArrayList<>(new LinkedHashSet<>(result));
223 //        System.out.println(result); 
224 //        
225 //        for(Object [] objs: result){
226 //            System.out.println(Arrays.asList(objs));
227 //        }
228     }

 

 

 

 

  

Hibernate的学习详解(4)

标签:

原文地址:http://www.cnblogs.com/liuqing-bk/p/4813193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!