一.spring与hibernate整合的关键

     SessionFactory的创建交由IOC容器来管理。

     原本SessionFactory的需要通过Configuration对象创建,

     SessionFactory sf = new Configuration().configure().buildSessionFactory();

    现可以通过spring配置,依赖IOC容器,DI注入来实现。

二.整合步骤

  1.导入hibernate,spring,数据库连接所需要的jar包

  2.配置hibernate.cfg.xml文件,xxx.hbn.xml对象映射文件,spring配置文件

  3.创建测试类测试

三.实践

3.1先建立javabean,创建了一个user,只有简单的id,name两个属性

public class user {
    
	private int id;
	private String name;
	
	@Override
	public String toString() {
		return "user [id=" + id + ", name=" + name + "]";
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

3.2配置文件的配置

hibernate.cfg.xml文件的配置如下:

​
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
      	
        
<hibernate-configuration>
    <session-factory>
    
    	<!-- 数据库连接的参数配置 -->
    	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mybase</property>
    	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    	<property name="hibernate.connection.username">root</property>
    	<property name="hibernate.connection.password">root</property>
    	<!-- 通过数据库方言,告诉hibernate如何生产sql。 hibernate会根据配置的方言,生产符合当前数据库语言的SQL语句 -->
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    	
    	<!-- 其他常用配置 -->
    	<property name="hibernate.show_sql">true</property>
    	<!--  格式化输出sql语句-->
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
 
 		<!--加载的映射  -->
    	<mapping resource="hib/user.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

​

3.3user.hbn.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="hib">
	<class name="user" table="user">
		<id name="id" column="id">
			<generator class="native">
			</generator>
		</id>
		<property name="name" column="name"></property>
	</class>

</hibernate-mapping>

3.4spring配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"     
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           
    xmlns:context="http://www.springframework.org/schema/context"   		
    xmlns:aop="http://www.springframework.org/schema/aop"       			
    xmlns:tx="http://www.springframework.org/schema/tx"         
    xmlns:util="http://www.springframework.org/schema/util"         
    xmlns:p="http://www.springframework.org/schema/p"               
    xsi:schemaLocation="http://www.springframework.org/schema/beans                             
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        
                        http://www.springframework.org/schema/context                           
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd    
                        http://www.springframework.org/schema/aop                               
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                        http://www.springframework.org/schema/tx                            
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd                      
                        http://www.springframework.org/schema/util                          
                        http://www.springframework.org/schema/util/spring-util-3.0.xsd">  
                        
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="hibernate.cfg.xml"></property>
	</bean>                     

</beans>

四.测试类的创建.

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
	@Test
	public void test(){
		ApplicationContext ac =  new ClassPathXmlApplicationContext("Application.xml");
		SessionFactory sf = (SessionFactory)ac.getBean("sessionFactory");
		Session session = sf.openSession();
		Transaction ts = session.beginTransaction();
		user u = (user)session.get(user.class, 1);
		System.out.println(u);
		System.out.println("success!!!");
		ts.commit();
		session.close();
	}
}

五.结果

测试时在数据库先创建好表,写入一个数据,通过junit进行测试。

结果:

六.spring文件配置的另一种方式

可以不需要配置hinernate.cfg.xml文件,全部都在spring配置文件中配置,结果一样的

    <!-- 1.实例化连接池 -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybase"></property>
    	<property name="user" value="root"></property>
    	<property name="password" value="root"></property>
   </bean>
   
   <!--1. 定义一个sessionFactory -->
   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   	  <!-- 注入数据库对象 -->
   	  <property name="dataSource" ref="dataSource"></property>
   	  <!-- 映射配置 -->
   	  <property name="mappingResources">
   	  	<list>
   	  		<value>hib/user.hbm.xml</value>
   	  	</list>
   	  </property>
   	  <!-- 常用配置和数据库方言 -->
   	  <property name="hibernateProperties">
   	  	<props>
   	  		<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
   	  	</props>
   	  </property>
   </bean>
              

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐