S2SH框架整合(注解)Struts2+Spring+Hibernate+MySql

整合简介

Struts2+Spring4+hibernate4整合,Maven管理jar包,Eclipse工具。注解方式

架构截图

 

1、Spring整合Hibernate

1.1、创建Hibernate配置文件

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 8         <property name="hibernate.connection.password">root</property>
 9         <property
10  
11 name="hibernate.connection.url">jdbc:mysql://localhost:3306/woo0nise?characterEncoding=utf-8</property>
12         <property name="hibernate.connection.username">root</property>
13     </session-factory>
14 </hibernate-configuration>

 

该配置文件可以删除,下面会讲解到。

1.2Spring整合Hibernate

创建db.properties文件用于存放数据库配置文件

 

1 #数据库配置信息
2 #数据库链接驱动
3 jdbc.driver=com.mysql.jdbc.Driver
4 #数据库链接字符串
5 jdbc.url=jdbc:mysql://localhost:3306/woo0nise?characterEncoding=utf-8
6 #数据库用户名
7 jdbc.username=root
8 #数据库密码
9 jdbc.password=root

 

创建applicationConext.xml,用于配置dao

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4 xmlns:tx="http://www.springframework.org/schema/tx"
 5 xmlns:util="http://www.springframework.org/schema/util"
 6 xmlns:p="http://www.springframework.org/schema/p"
 7 xmlns:context="http://www.springframework.org/schema/context"
 8 xmlns:aop="http://www.springframework.org/schema/aop"
 9 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
11 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
12 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
13 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
14 <!-- 加载数据库配置文件 -->
15 <context:property-placeholder location="classpath:resource/db.properties" />
16 <!-- 配置DataSource (Druid数据源)-->
17 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"  >
18 <property name="driverClassName" value="${jdbc.driver}" ></property>
19 <property name="url" value="${jdbc.url}" ></property>
20 <property name="username" value="${jdbc.username}" ></property>
21 <property name="password" value="${jdbc.password}" ></property>
22 </bean>
23 <!-- 配置session工厂 -->
24 <bean id="sessionFactory"  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
25 <!-- 配置数据源 -->
26 <property name="dataSource" ref="dataSource" ></property>
27 <!-- 配置hibernate的信息 -->
28 <property name="hibernateProperties">
29 <props>
30 <prop key="hibernate.dialect">
31 org.hibernate.dialect.MySQLDialect
32 </prop>
33 <prop key="hibernate.show_sql">true</prop>
34 <prop key="hibernate.format_sql">true</prop>
35 </props>
36 </property>
37 <!-- 加载由注解定义的持久化类 -->
38 <property name="packagesToScan">
39 <list>
40 <value>com.test.entity</value>
41 </list>
42 </property>
43 </bean>
44 <!-- 定义Autowired,自动注入Bean -->
45 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" ></bean>
46 <!-- 配置事务 -->
47 <!-- 配置事务管理器 -->
48 <bean
49  id="transactionManager" 
50 class="org.springframework.orm.hibernate4.HibernateTransactionManager" 
51 p:sessionFactory-ref="sessionFactory" ></bean>
52 <!-- 使用事务注解方式 -->
53 <tx:annotation-driven transaction-manager="transactionManager" />
54 <context:component-scan base-package="com.test"></context:component-scan>
55 </beans>
applicationContext.xml

 

1、加载db.properties数据库配置文件

2、创建数据源用来创建sessionFctoty,需要数据库配置信息

3、创建sessionFactory用于产生session,需要数据源以及hibernate配置文件还有定义注解实体类的包

4、创建事务管理器,用于管理事务

5、创建事务

6、定义注解扫描器

 

1.3、创建struts.xml

 

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE
 3  struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 
 4 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
 5 <struts>
 6 <package name="default" namespace="/" extends="struts-default" >
 7 <action name="ok" class="com.test.web.UserAction" method="register" >
 8 <result name="success">/index.jsp</result>
 9 </action>
10 </package>
11 </struts>

 

1.4、配置web.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0" 
 3 xmlns="http://java.sun.com/xml/ns/javaee" 
 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 7   <display-name></display-name>
 8   <welcome-file-list>
 9     <welcome-file>index.jsp</welcome-file>
10   </welcome-file-list>
11   <filter>
12    <filter-name>struts2</filter-name>
13    <filter-class>
14    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
15    </filter-class>
16   </filter>
17   <filter-mapping>
18    <filter-name>struts2</filter-name>
19    <url-pattern>/*</url-pattern>
20   </filter-mapping>
21    <!-- 加载spring的配置文件 -->
22   <context-param>
23    <param-name>contextConfigLocation</param-name>
24    <param-value>classpath:spring/applicationContext.xml</param-value>
25   </context-param>
26   <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
27   </listener>
28  </web-app>
web.xml

 

3、测试整合

3.1、创建实体类

 

 1 package com.test.entity;
 2 import javax.persistence.Column;
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import static javax.persistence.GenerationType.IDENTITY;
 6 import javax.persistence.Id;
 7 import javax.persistence.Table;
 8 /**
 9  * User generated by hbm2java
10  */
11 @Entity
12 @Table(name = "user", catalog = "woo0nise")
13 public class User implements java.io.Serializable {
14 private Integer id;
15 private String username;
16 private String userpwd;
17 public User() {
18 }
19 public User(String username, String userpwd) {
20 this.username = username;
21 this.userpwd = userpwd;
22 }
23 @Id
24 @GeneratedValue(strategy = IDENTITY)
25 @Column(name = "id", unique = true, nullable = false)
26 public Integer getId() {
27 return this.id;
28 }
29 public void setId(Integer id) {
30 this.id = id;
31 }
32 @Column(name = "username", nullable = false)
33 public String getUsername() {
34 return this.username;
35 }
36 public void setUsername(String username) {
37 this.username = username;
38 }
39 @Column(name = "userpwd", nullable = false)
40 public String getUserpwd() {
41 return this.userpwd;
42 }
43 public void setUserpwd(String userpwd) {
44 this.userpwd = userpwd;
45 }
46 }

 

3.2、创建Dao层接口以及实现类

IUserDao

 

 1 package com.test.dao;
 2  
 3 import com.test.common.dao.BaseDao;
 4 import com.test.entity.User;
 5  
 6 /**
 7  * <p>Title:IUserDao</p>
 8  * <p>Description:</p>
 9  * <p>Company:www.hack-gov.com</p>
10  * @author 0nise
11  * @date 2016年12月29日 下午11:41:46
12  * @Email woo0nise@gmail.com
13  * @version 1.0
14  */
15 public interface IUserDao extends BaseDao<User> {
16  
17 }

 

UserDaoImpl

 

package com.test.dao.impl;
 
import org.springframework.stereotype.Repository;
import com.test.common.dao.BaseDaoImpl;
import com.test.dao.IUserDao;
import com.test.entity.User;
 
/**
 * <p>Title:UserDaoImpl</p>
 * <p>Description:</p>
 * <p>Company:www.hack-gov.com</p>
 * @author 0nise
 * @date 2016年12月29日 下午11:42:45
 * @Email woo0nise@gmail.com
 * @version 1.0
 */
@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements IUserDao {
 
}

 

3.3、创建Service层接口以及实现类

UserService

 

package com.test.service;
 
import com.test.entity.User;
 
/**
 * <p>Title:UserService</p>
 * <p>Description:</p>
 * <p>Company:www.hack-gov.com</p>
 * @author 0nise
 * @date 2016年12月29日 下午11:44:29
 * @Email woo0nise@gmail.com
 * @version 1.0
 */
public interface UserService {
void register(User user);
}

UserServiceImpl.java

package com.test.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.test.dao.IUserDao;
import com.test.entity.User;
import com.test.service.UserService;
/**
 * <p>Title:UserServiceImpl</p>
 * <p>Description:</p>
 * <p>Company:www.hack-gov.com</p>
 * @author 0nise
 * @date 2016年12月29日 下午11:45:30
 * @Email woo0nise@gmail.com
 * @version 1.0
 */
@Service//("userService")
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,timeout=5)
public class UserServiceImpl implements UserService {
@Autowired
private IUserDao userDao;
 
@Override
public void register(User user) {
userDao.save(user);
}
}

 

3.4、创建Action

UserAction

 

package com.test.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
 
import com.opensymphony.xwork2.ActionSupport;
import com.test.entity.User;
import com.test.service.UserService;
import com.test.service.impl.UserServiceImpl;
 
/**
 * <p>Title:UserAction</p>
 * <p>Description:</p>
 * <p>Company:www.hack-gov.com</p>
 * @author 0nise
 * @date 2016年12月29日 下午11:48:51
 * @Email woo0nise@gmail.com
 * @version 1.0
 */
public class UserAction extends ActionSupport {
/**
 * 
 */
private static final long serialVersionUID = -799685719203073064L;
 
@Autowired
private UserService userService;

public String register(){
User user = new User("admin25", "admin25");
try {
userService.register(user);
System.out.println("ok");
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

 

运行结果

 

工具类

BaseDao.java

 

 1 package com.test.common.dao;
 2  
 3 import java.io.Serializable;
 4 import java.util.List;
 5  
 6 /**
 7  * <p>Title:BaseDao</p>
 8  * <p>Description:</p>
 9  * <p>Company:www.hack-gov.com</p>
10  * @author 0nise
11  * @date 2016年12月29日 下午11:10:19
12  * @Email woo0nise@gmail.com
13  * @version 1.0
14  */
15 public interface BaseDao<T> {
16 /**
17  * 获取一个对象
18  * @author 0nise
19  * @date 2016年12月29日 下午11:23:48
20  * @Email woo0nise@gmail.com
21  * @param entityClazz
22  * @param id id编号
23  * @return
24  */
25 T get(Class<T> entityClazz , Serializable id);
26 /**
27  * 保存一个对象
28  * @author 0nise
29  * @date 2016年12月29日 下午11:24:11
30  * @Email woo0nise@gmail.com
31  * @param entity
32  * @return
33  */
34 Serializable save(T entity);
35 /**
36  * 更新对象
37  * @author 0nise
38  * @date 2016年12月29日 下午11:24:19
39  * @Email woo0nise@gmail.com
40  * @param entity 实体对象
41  */
42 void update(T entity);
43 /**
44  * 删除对象
45  * @author 0nise
46  * @date 2016年12月29日 下午11:24:32
47  * @Email woo0nise@gmail.com
48  * @param entity 实体对象
49  */
50 void delete(T entity);
51 /**
52  * 根据id删除对象
53  * @author 0nise
54  * @date 2016年12月29日 下午11:24:44
55  * @Email woo0nise@gmail.com
56  * @param entityClazz
57  * @param id id编号
58  */
59 void delete(Class<T> entityClazz , Serializable id);
60 /**
61  * 查询该对象集合
62  * @author 0nise
63  * @date 2016年12月29日 下午11:24:57
64  * @Email woo0nise@gmail.com
65  * @param entityClazz
66  * @return
67  */
68 List<T> findAll(Class<T> entityClazz);
69 /**
70  * 获取该对象的数量
71  * @author 0nise
72  * @date 2016年12月29日 下午11:25:12
73  * @Email woo0nise@gmail.com
74  * @param entityClazz
75  * @return
76  */
77 long findCount(Class<T> entityClazz);
78 /**
79  * hql查询
80  * @author 0nise
81  * @date 2016年12月29日 下午11:25:24
82  * @Email woo0nise@gmail.com
83  * @param hql
84  * @return
85  */
86 List<T> find(String hql);
87 /**
88  * 分页查询
89  * @author 0nise
90  * @date 2016年12月29日 下午11:25:34
91  * @Email woo0nise@gmail.com
92  * @param hql
93  * @param pageNo
94  * @param pageSize
95  * @return
96  */
97 List<T> findByPage(String hql,int pageNo, int pageSize);
98  
99 }
BaseDao.java

 

BaseDaoImpl.java

 

  1 package com.test.common.dao;
  2  
  3 import java.io.Serializable;
  4 import java.util.List;
  5  
  6 import org.hibernate.Query;
  7 import org.hibernate.SessionFactory;
  8 import org.springframework.beans.factory.annotation.Autowired;
  9  
 10 /**
 11  * <p>Title:BaseDaoImpl</p>
 12  * <p>Description:</p>
 13  * <p>Company:www.hack-gov.com</p>
 14  * @author 0nise
 15  * @date 2016年12月29日 下午11:11:50
 16  * @Email woo0nise@gmail.com
 17  * @version 1.0
 18  */
 19 public class BaseDaoImpl<T> implements BaseDao<T>
 20 {
 21 @Autowired
 22 private SessionFactory sessionFactory;
 23 public void setSessionFactory(SessionFactory sessionFactory)
 24 {
 25 this.sessionFactory = sessionFactory;
 26 }
 27 public SessionFactory getSessionFactory()
 28 {
 29 return this.sessionFactory;
 30 }
 31 /**
 32  * 获取一个对象
 33  * @author 0nise
 34  * @date 2016年12月29日 下午11:23:48
 35  * @Email woo0nise@gmail.com
 36  * @param entityClazz
 37  * @param id id编号
 38  * @return
 39  */
 40 @SuppressWarnings("unchecked")
 41 public T get(Class<T> entityClazz , Serializable id)
 42 {
 43 return (T)getSessionFactory().getCurrentSession()
 44 .get(entityClazz , id);
 45 }
 46 /**
 47  * 保存一个对象
 48  * @author 0nise
 49  * @date 2016年12月29日 下午11:24:11
 50  * @Email woo0nise@gmail.com
 51  * @param entity
 52  * @return
 53  */
 54 public Serializable save(T entity)
 55 {
 56 return getSessionFactory().getCurrentSession()
 57 .save(entity);
 58 }
 59 /**
 60  * 更新对象
 61  * @author 0nise
 62  * @date 2016年12月29日 下午11:24:19
 63  * @Email woo0nise@gmail.com
 64  * @param entity 实体对象
 65  */
 66 public void update(T entity)
 67 {
 68 getSessionFactory().getCurrentSession().update(entity);
 69 }
 70 /**
 71  * 删除对象
 72  * @author 0nise
 73  * @date 2016年12月29日 下午11:24:32
 74  * @Email woo0nise@gmail.com
 75  * @param entity 实体对象
 76  */
 77 public void delete(T entity)
 78 {
 79 getSessionFactory().getCurrentSession().delete(entity);
 80 }
 81 /**
 82  * 根据id删除对象
 83  * @author 0nise
 84  * @date 2016年12月29日 下午11:24:44
 85  * @Email woo0nise@gmail.com
 86  * @param entityClazz
 87  * @param id id编号
 88  */
 89 public void delete(Class<T> entityClazz , Serializable id)
 90 {
 91 getSessionFactory().getCurrentSession()
 92 .createQuery("delete " + entityClazz.getSimpleName()
 93 + " en where en.id = ?0")
 94 .setParameter("0" , id)
 95 .executeUpdate();
 96 }
 97 /**
 98  * 查询该对象集合
 99  * @author 0nise
100  * @date 2016年12月29日 下午11:24:57
101  * @Email woo0nise@gmail.com
102  * @param entityClazz
103  * @return
104  */
105 public List<T> findAll(Class<T> entityClazz)
106 {
107 return find("select en from "
108 + entityClazz.getSimpleName() + " en");
109 }
110 /**
111  * 获取该对象的数量
112  * @author 0nise
113  * @date 2016年12月29日 下午11:25:12
114  * @Email woo0nise@gmail.com
115  * @param entityClazz
116  * @return
117  */
118 public long findCount(Class<T> entityClazz)
119 {
120 List<?> l = find("select count(*) from "
121 + entityClazz.getSimpleName());
122 if (l != null && l.size() == 1 )
123 {
124 return (Long)l.get(0);
125 }
126 return 0;
127 }
128 /**
129  * hql查询
130  * @author 0nise
131  * @date 2016年12月29日 下午11:25:24
132  * @Email woo0nise@gmail.com
133  * @param hql
134  * @return
135  */
136 @SuppressWarnings("unchecked")
137 public List<T> find(String hql)
138 {
139 return (List<T>)getSessionFactory().getCurrentSession()
140 .createQuery(hql)
141 .list();
142 }
143 /**
144  * hql查询,条件
145  * @author 0nise
146  * @date 2016年12月29日 下午11:25:24
147  * @Email woo0nise@gmail.com
148  * @param hql
149  * @return
150  */
151 @SuppressWarnings("unchecked")
152 protected List<T> find(String hql , Object... params)
153 {
154 Query query = getSessionFactory().getCurrentSession()
155 .createQuery(hql);
156 for(int i = 0 , len = params.length ; i < len ; i++)
157 {
158 query.setParameter(i + "" , params[i]);
159 }
160 return (List<T>)query.list();
161 }
162 /**
163  * 分页查询
164  * @author 0nise
165  * @date 2016年12月29日 下午11:25:34
166  * @Email woo0nise@gmail.com
167  * @param hql
168  * @param pageNo
169  * @param pageSize
170  * @return
171  */
172 @SuppressWarnings("unchecked")
173 public List<T> findByPage(String hql,int pageNo, int pageSize)
174 {
175 return getSessionFactory().getCurrentSession()
176 .createQuery(hql)
177 .setFirstResult((pageNo - 1) * pageSize)
178 .setMaxResults(pageSize)
179 .list();
180 }
181 /**
182  * 分页查询,条件
183  * @author 0nise
184  * @date 2016年12月29日 下午11:25:34
185  * @Email woo0nise@gmail.com
186  * @param hql
187  * @param pageNo
188  * @param pageSize
189  * @return
190  */
191 @SuppressWarnings("unchecked")
192 protected List<T> findByPage(String hql , int pageNo, int pageSize
193 , Object... params)
194 {
195 Query query = getSessionFactory().getCurrentSession()
196 .createQuery(hql);
197 for(int i = 0 , len = params.length ; i < len ; i++)
198 {
199 query.setParameter(i + "" , params[i]);
200 }
201 return query.setFirstResult((pageNo - 1) * pageSize)
202 .setMaxResults(pageSize)
203 .list();
204 }
205 }
206 
207  
BaseDaoImpl.java

 

转载于:https://www.cnblogs.com/0nise/p/6337997.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值