【spring框架】spring整合hibernate初步

spring与hibernate做整合的时候,首先我们要获得sessionFactory。

我们一般只需要操作一个sessionFactory,也就是一个"单例",这一点很适合交给spring来管理。

下面的代码演示如何创建一个JDBC DataSource 和Hibernate SessionFactory:
<beans>
  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
  </bean>

  <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
      <list>
        <value>product.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
      </value>
    </property>
  </bean>

</beans>

org.springframework.orm.hibernate3.LocalSessionFactoryBean是spring提供的使用XML配置的sessionFactory,是不支持Annotation的。可以使用:
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean让sessionFactory支持Annotation注解的形式来配置。

改写为(加了Properties的配置,Properties里面提供了hibernate的一些配置,如方言等属性):
 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    	<property name="mappingResources">
      		<list>
        	<value>product.hbm.xml</value>
     		 </list>
    	</property>
    	<property name="hibernateProperties">
		<props>
		   <prop key="hibernate.dialect">
                        org.hibernate.dialect.MySQLDialect
                   </prop>
		   <prop key="hibernate.show_sql">true</prop>
		</props>
    	</property>
</bean>

可以看到hibernate的映射方式(mappingResources)是xml的,我们想注入一个使用Annnotation的注解实体类,可以这样改写:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    	<property name="annotatedClasses">
      		<list>
        	<value>cn.edu.hpu.model.user</value>
     		 </list>
    	</property>
    	<property name="hibernateProperties">
		<props>
		   <prop key="hibernate.dialect">
                        org.hibernate.dialect.MySQLDialect
                   </prop>
		   <prop key="hibernate.show_sql">true</prop>
		</props>
    	</property>
</bean>


做一下实验要引入hibernate的jar包
User的Annotation注解实体类写法:
User.java:
package cn.edu.hpu.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {
	private int id;
	private String name;

	@Id
	@GeneratedValue
	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;
	}
	
}

UserDaoImpl的save方法就要用SessionFactory进行数据库数据的add了:
package cn.edu.hpu.dao.Impl;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.model.User;

@Component("u")
public class UserDaoImpl implements UserDao{
	
	private SessionFactory sessionFactory;
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void save(User u) {
		Session s=sessionFactory.openSession();
		s.beginTransaction();
		s.save(u);
		s.getTransaction().commit();
		System.out.println("add success!!");		
	}
}
(中间出了一次错,java.lang.IllegalStateException: @Resource annotation requires a single-arg。问题出现在配置resource的时候出现错误!
解决方案!@resource配置在了get上(正确的是应该配置在set上))

测试类:
package cn.edu.hpu.service;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.model.User;

public class UserServiceTest {
	
	@Test
	public void testAdd() throws Exception{
		ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
		
		UserService userService=(UserService)ctx.getBean("userService");
		System.out.println(userService.getClass());
		User u=new User();
		u.setName("jack");
		userService.add(u);
		ctx.destroy();
	}
}

测试成功,数据库储存了一条名为"jack"的字段。

以上是初步的整合,下一次总结是进一步整合。

转载请注明出处:http://blog.csdn.net/acmman/article/details/44570923

你可能感兴趣的:(Hibernate,String)