当前位置: 代码迷 >> Web前端 >> maven筹建WEB项目5 - 添加hibernate
  详细解决方案

maven筹建WEB项目5 - 添加hibernate

热度:384   发布时间:2012-06-27 14:20:09.0
maven搭建WEB项目5 - 添加hibernate
    项目使用Hibernate作为数据持久层
    1、添加Hibernate的依赖,在pom.xml中添加
   
<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<exclusions>
				<exclusion>
					<artifactId>cglib</artifactId>
					<groupId>cglib</groupId>
				</exclusion>
				<exclusion>
					<artifactId>dom4j</artifactId>
					<groupId>dom4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
		</dependency>

    此项不仅添加了Hibernate还添中对JPA的支持

    2、配置Spring对Hibernate的支持,添加的配置文件要在web.xml中能够引用到
    添加jdbc.properties,用于保存数据库连接以及Hibernate各项参数
#dataSource for oracle
oracle.driverClass=oracle.jdbc.driver.OracleDriver
oracle.url=jdbc:oracle:thin:@localhost:1521:TRAIN
oracle.username=train
oracle.password=train
oracle.maxIdle=1
oracle.maxActive=10
oracle.dialect=pine.core.hibernate.dialect.Oracle10gDialect
oracle.show_sql=true
oracle.generateDdl=false
oracle.hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
oracle.hibernate.cache.use_second_level_cache=false
oracle.hibernate.max_fetch_depth=2


    添加applicationContext-resources.xml,注册datasource对象
<?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:tx="http://www.springframework.org/schema/tx" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
	   http://www.springframework.org/schema/beans/spring-beans-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/context 
	   http://www.springframework.org/schema/context/spring-context-3.0.xsd   
	   http://www.springframework.org/schema/jee 
	   http://www.springframework.org/schema/jee/spring-jee-3.0.xsd	   
	   http://www.springframework.org/schema/lang
	   http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
	   http://www.springframework.org/schema/security 
	   http://www.springframework.org/schema/security/spring-security-3.0.xsd">
	
	
	<!-- PropertyConfigurer for the dataSource -->
	<context:property-placeholder location="classpath:jdbc.properties"  />
	
	<bean id="OracleDS" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${oracle.driverClass}" />
		<property name="url" value="${oracle.url}" />
		<property name="username" value="${oracle.username}" />
		<property name="password" value="${oracle.password}" />
		<property name="maxIdle" value="${oracle.maxIdle}" />
		<property name="maxActive" value="${oracle.maxActive}" />
	</bean>
</beans>


    添加applicationContext-common.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"
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
	   http://www.springframework.org/schema/beans/spring-beans-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/context 
	   http://www.springframework.org/schema/context/spring-context-3.0.xsd   
	   http://www.springframework.org/schema/jee 
	   http://www.springframework.org/schema/jee/spring-jee-3.0.xsd	   
	   http://www.springframework.org/schema/lang
	   http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
	   http://www.springframework.org/schema/security 
	   http://www.springframework.org/schema/security/spring-security-3.0.xsd">
	
	<!-- PropertyConfigurer for the dataSource -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	
	<context:annotation-config />
	
	<aop:aspectj-autoproxy />

	<tx:annotation-driven transaction-manager="transactionManager" />
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="list*" read-only="true" />
            <tx:method name="*" read-only="false" rollback-for="RollBackAppException"/>
        </tx:attributes>
    </tx:advice>

	<aop:config>
        <aop:advisor id="managerTx" advice-ref="txAdvice" pointcut="execution(* *..service.*Service.*(..))" order="2"/>
    </aop:config>
    
	<context:component-scan base-package="pine.web.dao"/>
	<context:component-scan base-package="pine.web.service"/>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="OracleDS" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${oracle.dialect}</prop>
				<prop key="hibernate.cache.use_second_level_cache">${oracle.hibernate.cache.use_second_level_cache}</prop>
				<prop key="hibernate.cache.provider_class">${oracle.hibernate.cache.provider_class}</prop>
				<prop key="hibernate.max_fetch_depth">${oracle.hibernate.max_fetch_depth}</prop>
				<prop key="hibernate.show_sql">${oracle.show_sql}</prop>
			</props>
		</property>
		<property name="packagesToScan">
			<list>
				<value>pine.web.model</value>
			</list>
		</property>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
</beans>


    3、创建表
create table SYS_USER
(
  ID            NUMBER not null primary key,
  USERNAME      VARCHAR2(50),
  PASSWORD      VARCHAR2(50),
  FULLNAME      VARCHAR2(100),
  DEPARTMENT_ID NUMBER
)


    4、创建实体类
@Entity
@Table(name="SYS_USER")
public class User implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_USER")
	@SequenceGenerator(name="SEQ_USER", sequenceName="SEQ_USER")
	private Long id;
	
	private String username;
	
	private String password;
	
	private String fullname;
        
        ......(各种get,set方法)
}


    5、创建Dao
    创建系统基础DAO类AbstractHibernateDao
public abstract class AbstractHibernateDao extends HibernateDaoSupport {

	@Resource(name="sessionFactory")
    public void setSuperSessionFactory(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }
}


    创建基础DAO接口,只提供了部分方法
public interface BaseDao<T> {
	
	public void save(T t);
	
	public T get(Serializable id);
	
	public T load(Serializable id);
	
	public void delete(Serializable id);
	
	public void delete(T t);
	
	public void delete(T t, LockMode lockMode);
	
	public void deleteAll(Collection<T> entities);
}


    创建基础DAO接口实现类
public abstract class BaseDaoImpl<T> extends AbstractHibernateDao implements
		BaseDao<T> {
	
	private Logger log = Logger.getLogger(BaseDaoImpl.class);
	
	protected abstract Class<T> getEntityClass();

	public void save(T t) {
		getHibernateTemplate().save(t);
	};
	
	@Override
	public T get(Serializable id) {
		return getHibernateTemplate().get(getEntityClass(), id);
	}
	
	@Override
	public T load(Serializable id) {
		T ob = null;
		try {
			ob = getHibernateTemplate().load(getEntityClass(), id);
		} catch (RuntimeException e) {
			if(log.isDebugEnabled())
				log.debug("can't load entity by primary key", e);
		}
		if (ob == null) 
			return get(id);
		return null;
	}
	
	@Override
	public void delete(Serializable id) {
		T ob = load(id);
		if (ob == null) {
			if(log.isDebugEnabled())
				log.debug("can't delete entity by primary key:"+getEntityClass().getName()+"."+id+",object is not exist!");
			return;
		}
		getHibernateTemplate().delete(ob);
	}
	
	@Override
	public void delete(T t) {
		getHibernateTemplate().delete(t);
	}
	
	@Override
	public void delete(T t, org.hibernate.LockMode lockMode) {
		getHibernateTemplate().delete(t, lockMode);
	}
	
	@Override
	public void deleteAll(Collection<T> entities) {
		getHibernateTemplate().deleteAll(entities);
	}
	
}


    创建UserDao,UserDaoImpl,UserService,UserServiceImpl各种类

  
 @Service("UserService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	
	@Override
	public void save(User user) {
		this.userDao.save(user);
	}
	
	@Override
	public void test() {
		User user = new User();
		user.setId(1L);
		user.setUsername("gmm");
		user.setPassword("admin");
		user.setFullname("龚敏");
		save(user);
	}
}


    5、测试一下
  相关解决方案