欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring整合Hibernate

程序员文章站 2022-04-14 21:50:10
...

此篇注释参见 Review_one 工程
一切都是在整合完Hibernate基础上进行的

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="show_sql">true</property>

        <property name="connection.url">

        jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8

        </property>

        <property name="dialect">

        org.hibernate.dialect.MySQLDialect

        </property> 

        <property name="connection.username">root</property>

        <property name="connection.password">mysql</property>

        <property name="connection.driver_class">

        com.mysql.jdbc.Driver

        </property>

        <mapping resource="com/pojo/Password.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

方法一:加载配置方案1:在spring配置中放置hibernate.cfg.xml配置信息
(只需引hibernate.cfg.xml文件)

第一步:
applicationContext.xml(已经导入四个约束情况下)

<bean id="sessionFactory"
	class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

	<property name="hibernateProperties">
		<props>
			<prop key="hibernate.dialect">
				org.hibernate.dialect.MySQLDialect
			</prop>
		</props>
	</property>
	<property name="configLocation" value="classpath:hibernate.cfg.xml"></property> 
	</bean>

配置.hbm.xml部分可以写成:
1.

	<property name="configLocation" value="classpath:hibernate.cfg.xml"></property> 
 <property name="mappingDirectoryLocations" value="classpath:com/pojo"></property> 


Test部分:

//不要把导入的包弄错了
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.annotation.Resource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.ContextConfiguration;

import com.pojo.Password;

 //这两个@是为了运行Junit而写
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HibernateTest {
    @Resource(name="sessionFactory")
    private SessionFactory sf;
    
    //选中test1,右击Run as ==JUnit Test
    @Test
    public void test1() throws SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException, SystemException{
    	Session session=sf.openSession();
    	Transaction tx=session.beginTransaction();
    	Password password1=new Password();
    	password1.setAccount("666");
    	password1.setPassword("666");
    	session.save(password1);
    	tx.commit();
    	session.close();
    }
}


方法二:只需引入Password.hbm.xml,hibernate.cfg.xml可删除
<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 -->
    <bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource">  //此步要加commons-dbcp.jar
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver">
		</property>
		<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="mysql"></property>
		  
	</bean> 
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> //此步要加spring-orm-4.2.4.RELEASE.jar
		<property name="dataSource" ref="dataSource"></property> 
		<property name="hibernateProperties">
			<props>
			 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
			</props>
		</property>
	
		<property name="mappingResources">
			<list>
				<value>com/pojo/Password.hbm.xml</value>
			</list>
		</property>  
<bean>



扩展:
配置applicationContext.xml中的sessionFactory部分可以换成(第一种):

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
   <property name="hibernateProperties">
      <props>
         <!-- 必选配置 -->
         <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</prop>
         <prop key="hibernate.connection.username">root</prop>
         <prop key="hibernate.connection.password">mysql</prop>
         <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <!--  可选配置 -->
         <prop key="hibernate.show_sql">true</prop>
         <prop key="hibernate.format_sql">true</prop>
         <prop key="hibernate.hbm2ddl.auto">update</prop>
      </props>
   </property>

   

 


配置sessionFactory部分可以换成(第二种):
先加入一个db.properties

# 连接mysql地址
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8

# mysql数据库驱动
jdbc.driverClass=com.mysql.jdbc.Driver
# mysql数据库用户名
jdbc.user=root
# mysql数据库密码
jdbc.password=mysql

applicationContext.xml中写:

<!-- 读取db.properties文件 -->
<context:property-placeholder location="classpath:db.properties"/>

 <!--需要c3p0-0.9.2.1.jar  hibernate-c3p0-5.0.7.Final.jar mchange-commons-java-0.2.3.4.jar-->
 <!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
  <property name="driverClass" value="${jdbc.driverClass}"></property>
  <property name="user" value="${jdbc.user}"></property>
  <property name="password" value="${jdbc.password}"></property>
</bean>

 <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
   <property name="dataSource" ref="dataSource"></property>
   <property name="hibernateProperties">
      <props>
        <!-- 必选配置 -->
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <!-- 可选配置 -->
         <prop key="hibernate.show_sql">true</prop>
         <prop key="hibernate.format_sql">true</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop> 
      </props>
   </property>

Dao部分:
第一种:直接用hibernate方法:

Password password1=new Password();
    	password1.setAccount(account);
    	password1.setPassword(password);
    	
    	Configuration conf=new Configuration().configure();
    	
    	SessionFactory sessionFactory=conf.buildSessionFactory();
    	
    	Session session=sessionFactory.openSession();
    	
    	//以上三步可以省略,可以用HibernateSessionFactory(前提是必须先创建)调用静态方法
    	
    	Transaction tx=null;
    	
    	try {
        	tx=session.beginTransaction();
            session.save(password1);
        	tx.commit();
        	
		} catch (Exception e) {
			if(tx!=null){
		  		tx.rollback();
		  	   }
			e.printStackTrace();
			
		}finally{
		   session.close();
		   sessionFactory.close();
		   return true;
		}


第二种:用sessionFactory

package com.daoImpl;
import javax.annotation.Resource;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.ContextConfiguration;

import com.pojo.Password;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HibernateTest {
    @Resource(name="sessionFactory")
    private SessionFactory sf;
    
    @Test
    public void test1() throws SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException, SystemException{
    	Session session=sf.openSession();
    	Transaction tx=session.beginTransaction();
    	Password password1=new Password();
    	password1.setAccount("000");
    	password1.setPassword("666");
    	session.save(password1);
    	tx.commit();
    	session.close();
    }
}

第三种:用loginDao和this.getHibernateTemplate()

package com.daoImpl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.dao.LoginDao;
import com.pojo.Password;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HibernateTest2 extends HibernateDaoSupport{
   @Resource(name="loginDao")
   private LoginDao login;
   
       @Autowired
	   public void setSessionFactory0(SessionFactory sessionFactory){  
	      super.setSessionFactory(sessionFactory);  
	   }
	
   @Test
   public void fun1(){
	   Password p=login.getByCode("000");  //调用实现类方法
	   System.out.println(p.getAccount());
   }
   
   @Test
   public void fun2(){
	   	Password password1=new Password();
	   	password1.setAccount("000");
	   	password1.setPassword("000");
	   List li= (List)this.getHibernateTemplate().find("from Password p where p.account=?","000");
       System.out.println(li.get(0).toString());
   }
}


Action中写
第一种方法:(两个bean必须分离且有ref)

 private LoginService loginService;
	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

applicationContext中写

<bean id="LoginAction" class="com.action.LoginAction" scope="prototype">
   <property name="loginService" ref="loginService"></property>   
</bean>

第二种方法:

@Resource(name="loginService")  //就比第一种方法多了这一行
private LoginService loginService;
  
	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

applicationContext中写

<bean id="LoginAction" class="com.action.LoginAction" scope="prototype">
   <property name="loginService" ref="loginService"></property>   
</bean>

第三种方法:

Action里写:

public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    LoginService loginService=(LoginService) context.getBean("loginService");

applicationContext中写:

<bean id="LoginAction" class="com.action.LoginAction" scope="prototype">
   <property name="loginService" ref="loginService"></property>   
</bean>

第四种方法:(两个bean必须分离且无ref)
Action里写:

@Resource(name="loginService")
    private LoginService loginService;
    
 applicationContext中写:(两个bean必须分离且无ref)
<bean id="LoginAction" class="com.action.LoginAction" scope="prototype">   </bean>
<bean id="loginService" class="com.serviceImpl.LoginServiceImpl">
   <property name="loginDao" ref="loginDao"></property>  //有或没有都可以
</bean>

第五种方法:(两个bean必须分离且无ref)
Action里写:

 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    LoginService loginService=(LoginService) context.getBean("loginService");

applicationContext中写:

<bean id="LoginAction" class="com.action.LoginAction" scope="prototype">   </bean>
<bean id="loginService" class="com.serviceImpl.LoginServiceImpl">
   <property name="loginDao" ref="loginDao"></property>  //有或没有都可以
</bean>

**三种方法总结注意:**属性写在哪里,如果

而在LoginAction类里又有 loginService属性, 则必须出现setter方法(重要) 如果没有出现 ,则不需要setter方法 注释代替xml也需要注意

注意:下例中的ref如何写
applicationContext里写:

 <bean name="loginDao" class="com.daoImpl.LoginDaoImpl">
<!-- 注入sessionFactory,dao需要先继承HibernateDaoSupport才会有sessionFactory属性 -->
 <property name="sessionFactory" ref="sessionFactory"></property> 
</bean> 

那在LoginDaoImpl中

public class LoginDaoImpl extends HibernateDaoSupport implements LoginDao{

	@Autowired
	   public void setSessionFactory0(SessionFactory sessionFactory){  
	      super.setSessionFactory(sessionFactory);  
	   }
相关标签: Spring整合Hibernate