标签:
spring整合hibernate
1、hibernate使用注解。
daoImpl需要继承HibernateDaoSupport对象,针对给对象的getHibernateTemplate()进行hibernate操作。操作的语句是hql语句。
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>jdbc.properties</value> </list> </property> </bean> <bean id="propertyConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="properties" ref="configProperties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="url" value="${jdbc.url}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" destroy-method="destroy"> <property name="dataSource" ref="dataSource"></property> <property name="annotatedPackages" value="classpath:com" /> 该package下的所有类都会当成实体类加载 <property name="annotatedClasses"> 配置实体类 <list> <value>com.entity.Cat</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.dialect">${jdbc.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">saveorupdate</prop> 创建表结构 </props> </property> </bean>
<bean id="catDao" class="com.dao.CatDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Cat.java
package com.entity; import java.util.Date; import javax.jdo.annotations.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name="cat") public class Cat { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) //主键规则配置 private int id; @Column(name="name") private String name; @Column(name="createDate") @Temporal(value=TemporalType.TIMESTAMP) <!--Date类型在数据库里面设定 --> private Date createDate; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getCreateDate() { return createDate; } }
测试:
public static void method1(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); CatDao catdao=context.getBean("catDao",CatDao.class); /*Cat cat=new Cat(); cat.setName("喵咪"); cat.setCreateDate(new Date()); catdao.createCat(cat); List<Cat> cats=catdao.listCats(); for(int i=0;i<cats.size();i++){ System.out.println(cats.get(i).getId()+"\t"+cats.get(i).getName()+"\t"+cats.get(i).getCreateDate().toLocaleString()); }*/ Cat cat1=catdao.findCatByName("喵咪"); System.out.println(cat1.getId()+"\t"+cat1.getName()+"\t"+cat1.getCreateDate()); }
使用xml实现hibernate整合
1、sessionFactory的class由org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean变成了org.springframework.orm.hibernate3.LocalSessionFactoryBean
2、加入property名为mappingResources的注入实体类映射文件
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" destroy-method="destroy"> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"><!-- 配置实体类 --> <list> <value>com/entity/Dog.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.dialect">${jdbc.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">saveorupdate</prop><!-- 创建表结构 --></props> </property> </bean> <bean id="dogDao" class="com.dao.DogDaoImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
<?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> <class name="com.entity.Dog" table="Dog"> <id name="id" type="int"> <column name="id"></column> <generator class="identity" /> </id> <property name="name" type="string"> <column name="name"></column> </property> <property name="age" type="int"> <column name="age"></column> </property> </class> </hibernate-mapping> package com.entity; public class Dog { private int id; private String name; private int age; 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public static void method2(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); DogDao dogdao=context.getBean("dogDao",DogDao.class); /*Dog dog=new Dog(); dog.setName("旺旺"); dog.setAge(12); dogdao.createDog(dog);*/ List<Dog> dogs=dogdao.findAll(); System.out.println(dogs.get(0).getName()); } package com.dao; import java.util.List; import com.entity.Dog; public interface DogDao { public void createDog(Dog dog); public List<Dog> findAll(); public void updateDog(Dog dog); public Dog findDogByName(String name); } package com.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.entity.Dog; public class DogDaoImpl extends HibernateDaoSupport implements DogDao{ public void createDog(Dog dog) { // Session session=this.getSession(); //Transaction tx=session.beginTransaction(); // try{ /* 我现在要将事物配置在applicationContext中 */ this.getHibernateTemplate().save(dog); // tx.commit();} // catch(Exception e){ // tx.rollback(); // } } @SuppressWarnings("unchecked") public List<Dog> findAll() { List<Dog> dogs=this.getHibernateTemplate().find("from Dog"); return dogs; } public void updateDog(Dog dog) { // Session session=this.getSession(); // Transaction tx=session.beginTransaction(); // try{ this.getHibernateTemplate().update(dog); // tx.commit();} // catch(Exception e){ // tx.rollback(); // } } public Session createSession(){ Session session=this.getSession(); if(session==null||!session.isOpen()){ session=getHibernateTemplate().getSessionFactory().openSession(); } return session; } public void closeSession(){ this.getSession().close(); } @SuppressWarnings("unchecked") public Dog findDogByName(String name) { List<Dog> dogs=this.getHibernateTemplate().find("select d from Dog d where name=?",name ); if(dogs.size()>0){ Dog d=dogs.get(1); return d; } return null; } }
整合后使用hibernate事务管理
另外一半使用service类,方便aop
package com.service; import java.util.List; import com.entity.Dog; public interface DogService { public void createDog(Dog dog); public List<Dog> findAll(); public void updateDog(Dog dog); public Dog findDogByName(String name); } package com.service; import java.util.List; import com.dao.DogDao; import com.entity.Dog; public class DogServiceImpl implements DogService{ private DogDao dogDao; public void setDogDao(DogDao dogDao) { this.dogDao = dogDao; } public DogDao getDogDao() { return dogDao; } public void createDog(Dog dog) { dogDao.createDog(dog); } public List<Dog> findAll() { return dogDao.findAll(); } public Dog findDogByName(String name) { return dogDao.findDogByName(name); } public void updateDog(Dog dog) { dogDao.updateDog(dog); } }
<bean id="hibernateTransactionAttributeSource" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource"> <!-- 事务管理规则 --> <property name="properties"> <!-- 具备事务管理的方法名 --> <props> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="create*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <!-- hibernate 事务管理器 --> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="dogService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="hibernateTransactionManager"> </property> <property name="target"> <!-- 被管理的对象,匿名Bean --> <bean class="com.service.DogServiceImpl"> <property name="dogDao" ref="dogDao"></property> </bean> </property> <property name="transactionAttributeSource" ref="hibernateTransactionAttributeSource" /> <!-- 设置事务管理规则 --> </bean>
public static void method3(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); DogService dogservice=context.getBean("dogService",DogService.class); Dog d=new Dog(); d.setName("旺仔"); d.setAge(13); dogservice.createDog(d); }
标签:
原文地址:http://www.cnblogs.com/aigeileshei/p/5481141.html