spring学习笔记13--Spring2.x+Hibernate3.x +Struts1.x整合开发(1)sh先行组合

Spring2.x+Hibernate3.x +Struts1.x整合开发(jar会用冲突不要一次性全部整合,按照博文名称顺序整合)

最近复习spring相关知识,特记录于此,欢迎大家交流指正---QQ:767872620

一、搭建环境:

jar包:

二、代码示例

(1)首先是Spring2.x+Hibernate3.x 精华在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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-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/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	">


<!-- 配置数据源 -->
<bean id="dataSourceOrcl" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
	<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
	<property name="username" value="websb"/>
	<property name="password" value="ddit"/>
	<!-- 连接池启动时的初始值 -->
	<property name="initialSize" value="1"/>
	<!-- 连接池的最大连接数 -->
	<property name="maxActive" value="500"/>
	<!-- 最大空闲值,当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,直到减少到MaxIdle为止 -->
	<property name="maxIdle" value="2"/>
	<!-- 最小空闲值,当空闲的连接数少于两个值时,连接池就会预申请一些连接数,以免洪峰来时来不及申请 -->
	<property name="minIdle" value="1"/>
</bean>
<!--hibernate二级缓存的配置  只存在一个(单例) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSourceOrcl"/>
		<!-- hibernate映射源数据 可以多个-->
		<property name="mappingResources">
		<list>
		<value>cn/itcast/bean/Person.hbm.xml</value>
		</list>
	</property>
	<property name="hibernateProperties">
	<value>
		hibernate.dialect=org.hibernate.dialect.OracleDialect<!--方言  -->
		hibernate.hbm2ddl.auto=update <!-- 是否根据映射源文件生成表结构 -->
		hibernate.show_sql=false <!-- 是否打印sql -->
		hibernate.format_sql=false<!-- 是否格式化sql -->
	</value>
	</property>
</bean>
<!-- 配置事务管理 :spring提供的hibernate事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<!--只要是通过sessionFactory创建的事务都会纳入这个管理器进行管理  -->
	<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 采用@Transaction注解方式使用事务
transaction-manager:指定事务管理器
 -->
<tx:annotation-driven transaction-manager="txManager"/>
<context:annotation-config/>
<bean id="personService" class="cn.itcast.service.imp.PersonServiceBean"></bean>
</beans>

(2)简单而粗暴的person类
 

package cn.itcast.bean;
/**
 * 
 * @author Mars
 *
 */
public class Person {
	private  Integer id;
	private String name;
	/**
	 * bean中必须生成一个无参的构造函数,否则获得实体对象时出错
	 */
	public Person(){
		
	}
	
	public Person(String name){
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


(3)Peson.hbm.xml Hibernate与数据库实体映射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="cn.itcast.bean">
 <class name="Person" table="person">
  <!-- 对象标示符,类型可以不写,hibernate自己识别 -->
  <id name="id">
   <!-- 指定主键生成方式。
        native根据方言判定生成主键的方式
         -->
    <generator class="native"/> 
   <!--  <generator class="uuid.hex"/>-->
   <!-- <generator class="sequence">
    <param name="sequence">PERSONID_SEQ</param>
   </generator>-->

  </id>
  <!-- 设置属性 -->
  <property name="name" length="10" not-null="true" />
 </class>


</hibernate-mapping>


(4) 业务类接口

package cn.itcast.service;

import java.util.List;

import cn.itcast.bean.Person;

public interface PersonService {

	public abstract void save(Person person);

	public abstract void update(Person person);

	public abstract Person getPerson(Integer personid);

	public abstract void delete(Integer personid);

	public abstract List<Person> getPersons();

}


(5)业务层实现类

package cn.itcast.service.imp;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;
/**
 * 提取接口:右击——>Refactor->Ectract Interface
 * shift + alt+t+选择
 * 
 * 移出:
 * 右击——>Refactor->Move
 * @author Mars
 *
 *通过注解生成事务
 */
@Transactional
public class PersonServiceBean implements PersonService {
	/**
	 * @Resource默认按照名称注入
	 */
	@Resource private SessionFactory sessionFactory;
	public void save(Person person){
		/**
		 * getCurrentSession通过此方法获取受spring容器中事务管理的session
		 * 事务呢?
		 * 不用关心,在方法执行前已经打开,在方法之后行自动结束事务
		 */
		sessionFactory.getCurrentSession().persist(person);
	}
	/**
	 * 对已经成为实体对象person处于游离状态的情况惊醒更新.
	 * 更新对象之后变成托管对象
	 */
	public void update(Person person){
		sessionFactory.getCurrentSession().merge(person);
	}
	/**
	 * 对获取数据的方法不需要事务
	 * 
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Person getPerson(Integer personid){
		/**
		 * get有个数据装配的过程,从db中取出,之后进行封装成对象 
		 */
		return (Person)sessionFactory.getCurrentSession().get(Person.class, personid);
	}
	
	public void delete(Integer personid){
		/**
		 * load与get相比少了数据封装的过程,应该是直接从缓存取,效率快了许多
		 */
		sessionFactory.getCurrentSession().delete(
				sessionFactory.getCurrentSession().load(Person.class, personid)
		);
	}
	/**
	 * 使用hql查询语言,获取所有数据
	 */
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<Person>getPersons(){
		
		return  sessionFactory.getCurrentSession().createQuery("from Person").list();
	}
}

(6)粗暴的单元测试类

package junit.test;

import static org.junit.Assert.fail;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;

public class PersonServiceTest {
	private static PersonService persionService;
	/**
	 * 测试时最先执行,可将一些初始化工作放在其中
	 * @throws Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
			persionService=(PersonService)applicationContext.getBean("personService");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testSave() {
		persionService.save(new Person("小张"));
	}

	@Test
	public void testUpdate() {
		Person person=persionService.getPerson(181);
		/*****/
		person.setName("邵楠");
		persionService.update(person);
	}

	@Test
	public void testGetPerson() {
		Person person=persionService.getPerson(181);
		System.out.println(person.getName());
	}

	@Test
	public void testDelete() {
		persionService.delete(181);
	}

	@Test
	public void testGetPersons() {
		List<Person>persons=persionService.getPersons();
		for(Person person:persons){
			System.out.println(person.getName());
		}
	}

}



 

整合注意事项:
1.jsee选择1.4
2.修改编码方式为:utf-8
3.修改编译级别:jdk1.6

快捷键:

提取接口:右击——>Refactor->Ectract Interface * shift + alt+t+选择

文件移出: * 右击——>Refactor->Move

spring包下载地址
http://yinhe2726.iteye.com/blog/1192466
spring下载过程:
http://blog.sina.com.cn/s/blog_6b2757530101hcfl.html

hibernate.cache.use_second_level_cache=true
  hibernate.cache.use_query_cache=false
  hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
  
  
异常遭遇:
1.org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/apache/log4j/LogManager

需要导入下面这两句的人需要这个包

import org.apache.log4j.LogManager;

import org.apache.log4j.Logger;

用法

logger.debug("----------------");

这个包在apache网站上可以直接免费直接下载到,不过那上面都是英语的,找起来比较麻烦。


http://blog.csdn.net/liuweishikong/article/details/7916015

2.org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.OracleDialect
http://blog.163.com/princess_mjy/blog/static/917310432009964655764/
3.org.hibernate.exception.SQLGrammarException: could not get next sequence value
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
 at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:119)
 at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
 at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:154)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:110)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
 at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:645)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:619)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:623)
 at cn.itcast.service.imp.PersonServiceBean.save(PersonServiceBean.java:35)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
 at $Proxy9.save(Unknown Source)
 at junit.test.PersonServiceTest.testSave(PersonServiceTest.java:32)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
 at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
 at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
 at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
 at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
 at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: 序列不存在

 at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
 at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
 at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
 at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
 at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
 at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1030)
 at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
 at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:785)
 at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:860)
 at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
 at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3381)
 at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3425)
 at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1490)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
 at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:98)
 ... 44 more

主键生成
http://fhqdddddd.blog.163.com/blog/static/18699154200822795037757/
http://bbs.csdn.net/topics/310132707

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值