时下流行的开发模式:Spring+Hibernate+Struts,在这里我介绍一下Spring+Hibernate的结合,加入Struts表示层那是非常简单的事情了。话不多说,让我们现在开始:
数据库准备:
数据库名称:AT_SMS
表名称:admin
字段如下:
sid bigint 从1开始自动增加,步长为1,单独做表的主键
name varchar(50)
password varchar(50)
开发软件准备:
Eclipse 3.1
MyEclipse Enterprise Workbench v4.1.1 GA
JDK1.4.2
Spring1.2[MyEclipse自带的]
Hibernate3.0[MyEclipse自带的]
步骤:
1、设定自己的WorkSpace[D:\Eclipse3.1\MyWorkspace];
2、建立普通Java工程[不是MyEclipse Web工程]MyProject[D:\Eclipse3.1\MyWorkspace\MyProject;
2A、配置数据库连接备用。东东在Window->Open Perspective->My Eclipse Database Explore下。在左边空白框点右键选择New,弹出框后填写Profile name:MyTestDB;驱动点Configure database driver去配置,其它的看着填,不想看到所以数据库就在第二步选择Display the selected schemas,点按钮Add时会自动连接数据库显示所有的数据,选择你想看到的,在这我们选择AT_SMS,点finish完成了。
3、添加Spring相关东西[点击菜单MyEclipse->Add SPring Capabilities...][注意:把光标停在工程根目录才能添加,不然是灰灰的];弹出窗口默认选中Spring1.2 Core包,把Spring1.2 ORM/DAO/Hibernate3选中,把Spring1.2 AOP,Spring1.2 Testing都选中[省得测试时候遇到找不到jar再去导入],next,创建一个src目录存放配置文件,finish。
4、添加Hibernate相关东西,注意根Spring关联起来,数据库连接选择之前创建的MyTestDB即可,Dialect默认是Sysbase,我用Sql Server,所以要改过来;Hibernate的bean ID设成跟Spring的一样,结果配置文件提示ID不唯一,哈哈,那就清除Hiebernate相关的东西先,这还有些麻烦,首先要切换到MyEclipse J2EE Development[如果没有这个可能是你的工作区没有这种工程,去创建一个MyEclipseJ2EE工程],接着把工程视图从PackageExplorer切换到Navigator,删除文件名带Hibernate字样的文件,打开.project文件,删除里头关于Hibernate的一个buildCommand,和一个nature.Ok了,可以重新添加Hibernate相关的东西.[注意:SessionFactory就是Spring用来关联Hibernate的那Bean的ID我填SessionFactory,填写数据库参数时的那个BeanID就是数据源名称,我填dataSource]
5、接下来产生Hibernate映射,将视图切换到MyEclipse Database Explorer,点右键打开连接,选择你要产生Java代码的表,我们在这选择admin,弹出窗口发现会默认带出一些参数,由于这个DB连接不是属于单个工程的是个全局的东东,默认参数可能不是你想要的,不管那么多你选择Java src folder到你当前工程的src目录,这就与你的工程关联起来了,参数也跟着变了,Java package设为com.kama.hibernate,选中产生Spring DAO;其它默认,表的主键产生要设置一些,选中表名,在ID Generator选择native;就这样了。
6、让Spring管理数据库事务,在配置文件applicationContext.xml中添加内容:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="SessionFactory"/>
</property>
</bean>
<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="regedit*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="do*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="autoProxyCreator"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>baseTransactionProxy</value>
</list>
</property>
<property name="beanNames">
<value>*DAO</value>
</property>
</bean>
7、事务中,必须是接口调用,具体原因请看其它资料,现在我们增加接口:AdoInterface,在其中定义方法:public void save(Object transientInstance);[用Object做参数类型是为了让所有DAO类共用这个接口];
8、AdminDAO中增加实现接口AdoInterface,修改其save方法的声明,public void save(Object transientInstance)
9、测试方法一,写如下代码来测试:
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AdoInterface dao = (AdoInterface) ctx.getBean("AdminDAO");
System.out.println(dao.toString());
Admin admin = new Admin();
admin.setName("Kama");
admin.setPassword("123456");
dao.save(admin);
System.out.println("--测试完毕--");
看到插入的记录了吧!
10、测试方法二:在工程属性的JAVA Builder path->Libraries里头设置导入D:\MyEclipse\eclipse\plugins\com.genuitec.eclipse.springframework_4.1.1\data\1.2\lib\spring-mock.jar
产生测试类继承org.springframework.test.AbstractTransactionalSpringContextTests;修改:
protected String[] getConfigLocations() {
return new String[]
{ "/applicationContext.xml" };
}
增加:
private AdoInterface adminDAO;
public void setAdminDAO(AdoInterface adminDAO)
{
this.adminDAO = adminDAO;
}
public void testSave()
{
this.setComplete();//想将数据插入数据库就保留这个,不想插入数据库,去掉这句Junit测试会自动回滚。
Admin admin = new Admin();
admin.setName("KamaSupport");
admin.setPassword("123456");
this.adminDAO.save(admin);
}
以Junit形式运行测试程序。大功告成!
附录A:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>net.sourceforge.jtds.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:jtds:sqlserver://127.0.0.1:3344/AT_SMS;SelectMethod=cursor</value>
</property>
<property name="username">
<value>sa</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="SessionFactory"/>
</property>
</bean>
<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="regedit*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="do*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="autoProxyCreator"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>baseTransactionProxy</value>
</list>
</property>
<property name="beanNames">
<value>*DAO</value>
</property>
</bean>
<bean id="SessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/kama/hibernate/Admin.hbm.xml</value>
</list>
</property>
</bean>
<bean id="AdminDAO" class="com.kama.hibernate.AdminDAO">
<property name="sessionFactory">
<ref bean="SessionFactory" />
</property>
</bean>
</beans>
附录B:log4j.properties
log4j.rootLogger=INFO,default
log4j.logger.org=ERROR
log4j.logger.com.comp=ERROR
log4j.logger.net.sf.hibernate=ERROR
log4j.logger.net.sf.hibernate.SQL=ERROR
log4j.logger.net.sf.hibernate.type=ERROR
log4j.logger.net.sf.ehcache=ERROR
log4j.logger.org.springframework=ERROR
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}:[%p] [%t] %r %l %m%n
log4j.appender.default=org.apache.log4j.RollingFileAppender
log4j.appender.default.Threshold=DEBUG
log4j.appender.default.File=kama.log
log4j.appender.default.Append=true
log4j.appender.default.MaxFileSize=1000KB
log4j.appender.default.MaxBackupIndex=3
log4j.appender.default.layout=org.apache.log4j.PatternLayout
log4j.appender.default.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}:[%p] [%t] %r %l %m%n