HibernateTemplate

Posted 呦,你是个老母猪呦!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HibernateTemplate相关的知识,希望对你有一定的参考价值。

org.springframework.orm.hibernate5.HibernateTemplate

这是spring-orm-4.3.4.RELEASE.jar包中的一个类,这个类是对Hibernate进行了封装;

这是可以进行注入的属性,需要注入sessionFactory属性,因此我们需要创建一个sessionFactory的Bean:

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref=""></property>
    </bean>

创建sessionFactory需要用到

org.springframework.orm.hibernate5.LocalSessionFactoryBean

这是spring-orm-4.3.4.RELEASE.jar包中的类

可注入的属性有:

 将sessionFactory注入到hibernateTemplate中:

 1     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
 2         <property name="sessionFactory" ref="sessionFactory"></property>
 3     </bean>
 4     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
 5         <property name="dataSource" ref="需要注入数据源"></property>
 6         <property name="hibernateProperties">
 7             <props>
 8                 <prop key="hibernate.dialect">org.hibernate.dialect.mysqlDialect</prop>
 9                 <prop key="hibernate.show_sql">true</prop>
10                 <prop key="hibernate.format_sql">true</prop>
11                 <prop key="hibernate.hbm2ddl.auto">update</prop>            
12                 <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>            
13             </props>
14         </property>
15         <property name="packagesToScan">
16             <array>
17                 <value>需要扫描的包</value>
18             </array>
19         </property>
20     </bean>
sessionFactory

 

创建sessionFactory还需要加载数据源和hibernate映射类的包;

    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh?serverTimezone=GMT&amp;useSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="zhangpn"></property>    

创建基类:

  1 package com.zhangpn.domain;
  2 
  3 import java.io.Serializable;
  4 
  5 import javax.persistence.Column;
  6 import javax.persistence.Entity;
  7 import javax.persistence.GeneratedValue;
  8 import javax.persistence.GenerationType;
  9 import javax.persistence.Id;
 10 import javax.persistence.Table;
 11 
 12 /**
 13  * 客户基类
 14  * 
 15  * @author Administrator
 16  *
 17  */
 18 
 19 @Entity
 20 @Table(name="cst_customer")
 21 public class Customer implements Serializable {
 22 
 23     @Id
 24     @Column(name="cust_id")
 25     @GeneratedValue(strategy=GenerationType.IDENTITY)
 26     private Long custId;
 27     
 28     @Column(name="cust_name")
 29     private String custName;
 30     
 31     @Column(name="cust_source")
 32     private String custSource;
 33     
 34     @Column(name="cust_industry")
 35     private String custIndustry;
 36     
 37     @Column(name="cust_level")
 38     private String custLevel;
 39     
 40     @Column(name="cust_address")
 41     private String custAddress;
 42     
 43     @Column(name="cust_phone")
 44     private String custPhone;
 45 
 46     public Long getCustId() {
 47         return custId;
 48     }
 49 
 50     public void setCustId(Long custId) {
 51         this.custId = custId;
 52     }
 53 
 54     public String getCustName() {
 55         return custName;
 56     }
 57 
 58     public void setCustName(String custName) {
 59         this.custName = custName;
 60     }
 61 
 62     public String getCustSource() {
 63         return custSource;
 64     }
 65 
 66     public void setCustSource(String custSource) {
 67         this.custSource = custSource;
 68     }
 69 
 70     public String getCustIndustry() {
 71         return custIndustry;
 72     }
 73 
 74     public void setCustIndustry(String custIndustry) {
 75         this.custIndustry = custIndustry;
 76     }
 77 
 78     public String getCustLevel() {
 79         return custLevel;
 80     }
 81 
 82     public void setCustLevel(String custLevel) {
 83         this.custLevel = custLevel;
 84     }
 85 
 86     public String getCustAddress() {
 87         return custAddress;
 88     }
 89 
 90     public void setCustAddress(String custAddress) {
 91         this.custAddress = custAddress;
 92     }
 93 
 94     public String getCustPhone() {
 95         return custPhone;
 96     }
 97 
 98     public void setCustPhone(String custPhone) {
 99         this.custPhone = custPhone;
100     }
101 
102     @Override
103     public String toString() {
104         return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
105                 + ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
106                 + ", custPhone=" + custPhone + "]";
107     }
108 
109 }
Customer基类

将packagesToScan属性进行注入,最终的applicationContext.xml内容是:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
 7         <property name="sessionFactory" ref="sessionFactory"></property>
 8     </bean>
 9     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
10         <property name="dataSource" ref="datasource"></property>
11         <property name="hibernateProperties">
12             <props>
13                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
14                 <prop key="hibernate.show_sql">true</prop>
15                 <prop key="hibernate.format_sql">true</prop>
16                 <prop key="hibernate.hbm2ddl.auto">update</prop>            
17                 <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>            
18             </props>
19         </property>
20         <property name="packagesToScan">
21             <array>
22                 <value>com.zhangpn.domain</value>
23             </array>
24         </property>
25     </bean>
26     <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
27         <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
28         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh?serverTimezone=GMT&amp;useSSL=false"></property>
29         <property name="user" value="root"></property>
30         <property name="password" value="zhangpn"></property>    
31     </bean>
32 </beans>
applicationContext.xml

再将事务管理配置:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
 8         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
 9 
10     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
11         <property name="sessionFactory" ref="sessionFactory"></property>
12     </bean>
13     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
14         <property name="dataSource" ref="datasource"></property>
15         <property name="hibernateProperties">
16             <props>
17                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
18                 <prop key="hibernate.show_sql">true</prop>
19                 <prop key="hibernate.format_sql">true</prop>
20                 <prop key="hibernate.hbm2ddl.auto">update</prop>            
21                 <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>            
22             </props>
23         </property>
24         <property name="packagesToScan">
25             <array>
26                 <value>com.zhangpn.domain</value>
27             </array>
28         </property>
29     </bean>
30     <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
31         <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
32         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh?serverTimezone=GMT&amp;useSSL=false"></property>
33         <property name="user" value="root"></property>
34         <property name="password" value="zhangpn"></property>    
35     </bean>
36     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
37         <property name="sessionFactory" ref="sessionFactory"></property>
38     </bean>
39     <tx:annotation-driven transaction-manager="transactionManager"/>    
40 </beans>
applicationContext.xml

(中间jdbcUrl有点小错误影响不大,修改过后以下是最终applicationContext.xml配置)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
 8         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
 9 <!-- Spring容器创建,扫描的包 -->
10     <context:component-scan base-package="com.zhangpn.*"></context:component-scan>
11 
12     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
13         <property name="sessionFactory" ref="sessionFactory"></property>
14     </bean>
15     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
16         <property name="dataSource" ref="datasource"></property>
17         <property name="hibernateProperties">
18             <props>
19                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
20                 <prop key="hibernate.show_sql">true</prop>
21                 <prop key="hibernate.format_sql">true</prop>
22                 <prop key="hibernate.hbm2ddl.auto">update</prop>            
23                 <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>            
24             </props>
25         </property>
26         <property name="packagesToScan">
27             <array>
28                 <value>com.zhangpn.domain</value>
29             </array>
30         </property>
31     </bean>
32     <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
33         <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
34         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh?serverTimezone=GMT"></property>
35         <property name="user" value="root"></property>
36         <property name="password" value="zhangpn"></property>    
37     </bean>
38     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
39         <property name="sessionFactory" ref="sessionFactory"></property>
40     </bean>
41     <tx:annotation-driven transaction-manager="transactionManager"/>    
42 </beans>
applicationContext.xml

测试主方法:

 1 package com.zhangpn.Test;
 2 
 3 import java.util.Iterator;
 4 import java.util.List;
 5 
 6 import org.hibernate.criterion.DetachedCriteria;
 7 import org.springframework.context.ApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 import org.springframework.orm.hibernate5.HibernateTemplate;
10 
11 import com.zhangpn.domain.Customer;
12 
13 public class Test {
14 
15     public static void main(String[] args) {
16         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
17         HibernateTemplate hibernateTemplate = (HibernateTemplate) applicationContext.getBean("hibernateTemplate");
18         DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
19         List<Customer> customers = (List<Customer>) hibernateTemplate.findByCriteria(dCriteria);
20         for (Customer customer : customers) {
21             System.out.println(customer);
22         }
23     }
24 
25 }
测试类

主要代码:

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        HibernateTemplate hibernateTemplate = (HibernateTemplate) applicationContext.getBean("hibernateTemplate");
        DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
        List<Customer> customers = (List<Customer>) hibernateTemplate.findByCriteria(dCriteria);
        for (Customer customer : customers) {
            System.out.println(customer);
        }
    }

最终,可以将数据库中的信息查询出来;

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Mon Jun 11 12:01:45 CST 2018 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.
Mon Jun 11 12:01:45 CST 2018 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.
Mon Jun 11 12:01:45 CST 2018 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: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_address as cust_add2_0_0_,
        this_.cust_industry as cust_ind3_0_0_,
        this_.cust_level as cust_lev4_0_0_,
        this_.cust_name as cust_nam5_0_0_,
        this_.cust_phone as cust_pho6_0_0_,
        this_.cust_source as cust_sou7_0_0_ 
    from
        cst_customer this_
Customer [custId=1, custName=张沛宁, custSource=1, custIndustry=长亮科技, custLevel=88级, custAddress=沛高中, custPhone=13613641361]
Customer [custId=2, custName=张沛龙, custSource=2, custIndustry=黑马科技, custLevel=45级, custAddress=沛高中, custPhone=13644441361]
Customer [custId=3, custName=刘晓云, custSource=3, custIndustry=瑞士科技, custLevel=55级, custAddress=徐一中, custPhone=13618582361]
Customer [custId=4, custName=zhangpn, custSource=5, custIndustry=American, custLevel=90, custAddress=江苏徐州, custPhone=13654874562]
Customer [custId=5, custName=小白, custSource=7, custIndustry=大学城, custLevel=20级, custAddress=常州大学, custPhone=13655479541]
Customer [custId=6, custName=zhangpn, custSource=5, custIndustry=American, custLevel=90, custAddress=刘德华, custPhone=13654874562]
Customer [custId=7, custName=44, custSource=666, custIndustry=22, custLevel=33, custAddress=11, custPhone=55]
Customer [custId=8, custName=搭建了, custSource=框架, custIndustry=你, custLevel=已经成功地, custAddress=恭喜, custPhone=SSH]

 findByCriteria方法:有两个用法;

第一种方法,不能分页;第二种方法,可以分页;

 findByCriteria意思是按照一定的标准去查找;那么这个标准是什么?我们怎么去定义这个标准?

答案是:Restrictions类


下面是 Restrictions的静态方法


 

举一个简单的例子:从表中查询custId为 5 的记录;

限制Restrictions定为:

Restrictions.eq("custId", 5L)

 

作为参数 :

    public static void main(String[] args) {
        ApplicationContext applicationContext = 以上是关于HibernateTemplate的主要内容,如果未能解决你的问题,请参考以下文章

hibernateTemplate中的回调函数

HibernateTemplate类的使用

集成Spring后HibernateTemplate实现分页

HibernateTemplate的使用

HibernateTemplate

HibernateTemplate和HibernateDaoSupport(spring注入问题)