前些天弄了一个Struts2+Spring3+iBatis的整合,第一部分:http://blog.youkuaiyun.com/ruantao1989/article/details/8143899第二部分:http://blog.youkuaiyun.com/ruantao1989/article/details/8143979第三部分:http://blog.youkuaiyun.com/ruantao1989/article/details/8144129
这回使用上次的程序,把iBatis剔除出去,ibatis的功能都用Hibernate实现,其实道理一样,就是具体配置牵扯到不少东西。
一共是两组action和service:
用户登录、注销是一个流程,用户管理是另一个流程,还和上次ssi一样。
这回时间紧,就简单罗列一下,相当于笔记,过些天要记得来补……
整合Hibernate和iBatis的主要区别是:
1.sessionFactory和hibernateTemplate代替iBatis的sqlMapClient
2.Hibernate可以用annotation管理实体
3.Hibernate的DaoImpl中要通过聚合的HibernateTemplate配合HQL实现SQL的具体操作
4.HibernateTemplateL的一些操作返回值和sqlMapClient不一样,比如不返回更改的数量
5.web.xml中,Hibernate需要OpenSessionInViewFilter
0.建表语句
DROP TABLE t_user;
CREATE TABLE t_user
(
userid NUMBER(9),
username VARCHAR2(50) NOT NULL,
password VARCHAR2(50) NOT NULL,
CONSTRAINT user_userid_pk PRIMARY KEY(userid)
);
commit;
1.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="" />
<!-- 1.JDBC配置:dataSource -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 2.sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- hibernate具体配置,分项写在下边 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 注入dataSource对象 -->
<property name="dataSource" ref="dataSource" />
<!-- 搜索带Annotation的实体 -->
<property name="packagesToScan">
<list>
<value>vo</value>
<!--<value>com.rt.sidemo....</value> -->
</list>
</property>
</bean>
<!-- Template -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 3.Spring 注入过程 -->
<bean id="User_SSH" class="vo.User_SSH" />
<!-- DAOImpl的注入 -->
<bean name="UserDao" class="dao.UserDaoImpl" >
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- Login的注入 -->
<bean name="LoginService" class="service.LoginService" >
<property name="user" ref="User_SSH"></property>
<property name="dao" ref="UserDao" />
</bean>
<bean name="Login" class="action.LoginAction">
<property name="service" ref="LoginService" />
</bean>
<!-- Manager的注入 -->
<bean name="ManagerService" class="service.ManagerService" >
<property name="user" ref="User_SSH"></property>
<property name="dao" ref="UserDao" />
</bean>
<bean name="UserManager" class="action.UserManagerAction">
<property name="service" ref="ManagerService" />
</bean>
<!-- 3.事务处理,需要配套的xmlns和schemaLocation -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="transactionManagerAdivice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="query*" propagation="REQUIRED" read-only="true" rollback-for="java.lang.RuntionException" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.RuntionException" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution( * service.*.*(..))"/>
<aop:advisor advice-ref="transactionManagerAdivice" pointcut-ref="allManagerMethod"/>
</aop:config>
</beans>
2.struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 指定Struts 2默认的ObjectFactory Bean - 交给Spring管理 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 中文防止乱码 -->
<constant name="struts.i18n.encoding" value="GBK"/>
<package name="struts2-spring" namespace="/" extends="struts-default">
<!-- 1.Login的Action-->
<action name="login" class="Login" method="login">
<result name="success">loginSuccess.jsp</result>
<result name="error">loginFail.jsp</result>
</action>
<action name="logOut" class="Login" method="logOut">
<result name="success">index.jsp</result>
</action>
<!-- 2.Manager的Action-->
<action name="register" class="UserManager" method="register">
<result name="success">operSuccess.jsp</result>
<result name="error">register.jsp</result>
</action>
<action name="queryall" class="UserManager" method="queryall">
<result name="success">manage.jsp</result>
</action>
<action name="update" class="UserManager" method="update">
<result name="success">operSuccess.jsp</result>
</action>
<action name="delete" class="UserManager" method="delete">
<result name="success">delSuccess.jsp</result>
</action>
</package>
</struts>
3.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- OpenSessionInViewFilter是Spring提供的一个针对Hibernate的一个支持类,
其主要意思是在发起一个页面请求时打开Hibernate的Session,一直保持这个Session,
直到这个请求结束,具体是通过一个Filter来实现的。
-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
以注册的数据流为例,用户管理类似,走另一个action和service而已
4.LoginAction.java
public class LoginAction extends ActionSupport
{
private String username;
private String password;
private ILogin service;
public LoginAction()
{
}
public String login()
{
boolean flag = false;
flag = service.login(getUsername(), getPassword());
if(true == flag)
{
Map<String, Object> attibutes = ActionContext.getContext().getSession();//记录用户登录信息
attibutes.put("username", username);
attibutes.put("password", password);//登录session
}
return flag==true?SUCCESS:ERROR;
}
public String logOut()
{
Map<String, Object> attibutes = ActionContext.getContext().getSession();
attibutes.remove("username");
return SUCCESS;
}
//setter&getter
5.LoginService.java
public class LoginService implements ILogin
{
private User_SSH user;
private IUserDao dao;
public boolean login(String username, String password)
{
user.setUsername(username);
user.setPassword(password);
List<User_SSH> l = dao.queryUserName(user.getUsername());
for(int i=0;i<l.size();i++)
{
String pwd = l.get(i).getPassword();
if(user.getPassword().equals(pwd))
return true;
}
return false;
}
//setter&getter
6.UserDaoImpl.java
public class UserDaoImpl implements IUserDao {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
//下边是HQL的具体实现
public List<User_SSH> queryUser() {
List<User_SSH> list = (List<User_SSH>)hibernateTemplate.find("from User_SSH");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
return list;
}
public boolean deleteUser(int id) {
User_SSH user = (User_SSH) hibernateTemplate.load(User_SSH.class,new Integer(id));
hibernateTemplate.delete(user);
return true;
}
public void insertUser(User_SSH u) {
System.out.println("ManagerService=>insertUser=>"+u);
hibernateTemplate.save(u);
}
public boolean updateUser(User_SSH u) {
hibernateTemplate.update(u);
return true;
}
public List<User_SSH> queryUserName(String name) {
String hql = "from User_SSH u where u.username IN ?";
List<User_SSH> users = new ArrayList<User_SSH>();
users = (List<User_SSH>)hibernateTemplate.find(hql,name);
return users;
}
}
=========================================================================================
遇到好几个bug,简单说下:
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
这是tomcat发出的警告,原因是“log4j的配置文件”没有出现在项目中
从之前项目拷贝一个过来就行了
org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: name of: vo.User_SSH [from vo.User_SSH t where t.name IN ?]; nested exception is org.hibernate.QueryException: could not resolve property: name of: vo.User_SSH [from vo.User_SSH t where t.name IN ?]
这个是因为HQL语句中字段和表中不对应,
我这儿把主键改成id了,hql里没改过来