[置顶] struts2+hibernate+spring整合(annotation版)
本博文使用struts2,hibernate,spring技术整合Web项目,同时分层封装代码,包含model层,DAO层,Service层,Action层。
在整合hibernate时使用annotation注释进行数据库的映射,整合spring时使用annotation进行IOC注入。
最后在DAO层中继承HibernateDaoSupport来编写代码。
首先看一下项目的目录:
需要的类库:
以person为例:
model层:
package com.hwadee.tradeUnion.model; import java.util.Date;
import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne; /**
* Person entity. @author MyEclipse Persistence Tools
*/
@Entity
public class Person implements java.io.Serializable { /**
*
*/
private static final long serialVersionUID = 1L;
// Fields private int id;
private String name;
private String sex;
private String nationality;
private String area;
private Date birthday;
private String education;
private String polity;
private String company;
private String idCard;
private String phone; //------------------------------------------
private Set<PersonApply> personApplys = new HashSet<PersonApply>();
private Set<Honour> Honours = new HashSet<Honour>();
private Death death; // Property accessors
@Id
@GeneratedValue
public int getId() {
return this.id;
} public void setId(int id) {
this.id = id;
} //-------------------------------------------------
@OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.ALL})
@JoinColumn(name="personId")
public Set<PersonApply> getPersonApplys() {
return personApplys;
} public void setPersonApplys(Set<PersonApply> personApplys) {
this.personApplys = personApplys;
} @OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.ALL})
@JoinColumn(name="personId")
public Set<Honour> getHonours() {
return Honours;
} public void setHonours(Set<Honour> honours) {
Honours = honours;
} @OneToOne
@JoinColumn(name="deathId")
public Death getDeath() {
return death;
} public void setDeath(Death death) {
this.death = death;
} //------------------------------------------------------ @Column(length = 30)
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} @Column(length = 10)
public String getSex() {
return this.sex;
} public void setSex(String sex) {
this.sex = sex;
} @Column( length = 10)
public String getNationality() {
return this.nationality;
} public void setNationality(String nationality) {
this.nationality = nationality;
} @Column( length = 50)
public String getArea() {
return this.area;
} public void setArea(String area) {
this.area = area;
} public Date getBirthday() {
return this.birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @Column( length = 10)
public String getEducation() {
return this.education;
} public void setEducation(String education) {
this.education = education;
} @Column(length = 10)
public String getPolity() {
return this.polity;
} public void setPolity(String polity) {
this.polity = polity;
} @Column( length = 30)
public String getCompany() {
return this.company;
} public void setCompany(String company) {
this.company = company;
} @Column(length = 18)
public String getIdCard() {
return this.idCard;
} public void setIdCard(String idCard) {
this.idCard = idCard;
} @Column(length = 11)
public String getPhone() {
return this.phone;
} public void setPhone(String phone) {
this.phone = phone;
} }
DAO层:
package com.hwadee.tradeUnion.dao; import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component; import com.hwadee.tradeUnion.model.Person; @Component
public class PersonDAO extends HibernateDaoSupport {
private static final Logger log = LoggerFactory.getLogger(PersonDAO.class);
// property constants
public static final String NAME = "name";
public static final String SEX = "sex";
public static final String NATIONALITY = "nationality";
public static final String AREA = "area";
public static final String EDUCATION = "education";
public static final String POLITY = "polity";
public static final String COMPANY = "company";
public static final String ID_CARD = "idCard";
public static final String PHONE = "phone"; protected void initDao() {
// do nothing
} //--------注入spring配置的sessionFactory
@Autowired
public void setMySessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
} public void save(Person transientInstance) {
log.debug("saving Person instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
} public void delete(Person persistentInstance) {
log.debug("deleting Person instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
} public void deleteById(int id){ Person temp=this.findById(id);
this.delete(temp); } public void update(Person temp){ getHibernateTemplate().update(temp); } public Person findById(int id) {
log.debug("getting Person instance with id: " + id);
try {
Person instance = (Person) getHibernateTemplate().get(
Person.class, id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
} public List findByExample(Person instance) {
log.debug("finding Person instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
} public List findByProperty(String propertyName, Object value) {
log.debug("finding Person instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Person as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
} public List findByName(Object name) {
return findByProperty(NAME, name);
} public List findBySex(Object sex) {
return findByProperty(SEX, sex);
} public List findByNationality(Object nationality) {
return findByProperty(NATIONALITY, nationality);
} public List findByArea(Object area) {
return findByProperty(AREA, area);
} public List findByEducation(Object education) {
return findByProperty(EDUCATION, education);
} public List findByPolity(Object polity) {
return findByProperty(POLITY, polity);
} public List findByCompany(Object company) {
return findByProperty(COMPANY, company);
} public List findByIdCard(Object idCard) {
return findByProperty(ID_CARD, idCard);
} public List findByPhone(Object phone) {
return findByProperty(PHONE, phone);
} public List findAll() {
log.debug("finding all Person instances");
try {
String queryString = "from Person";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
} public Person merge(Person detachedInstance) {
log.debug("merging Person instance");
try {
Person result = (Person) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
} public void attachDirty(Person instance) {
log.debug("attaching dirty Person instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
} public void attachClean(Person instance) {
log.debug("attaching clean Person instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
} public static PersonDAO getFromApplicationContext(ApplicationContext ctx) {
return (PersonDAO) ctx.getBean("PersonDAO");
}
//输入Hql查询函数
public List findByHql( String hql) {
log.debug("finding Admin By Hql");
try {
String queryString = hql;
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
}
Service层:
package com.hwadee.tradeUnion.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.hwadee.tradeUnion.dao.PersonDAO; import com.hwadee.tradeUnion.model.Person; @Component
public class PersonService { private PersonDAO personDAO; public PersonDAO getPersonDAO() {
return personDAO;
} @Resource
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
} public void add(Person kxw) { personDAO.save(kxw); } public void delete(Person kxw) { personDAO.delete(kxw);
} public void deleteById(int id) { personDAO.deleteById(id);
} public List<Person> list() { return personDAO.findAll(); } public Person loadById(int id) { return personDAO.findById(id);
} public void update(Person kxw) { personDAO.update(kxw); }
Action层:
package com.hwadee.tradeUnion.action; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.hwadee.tradeUnion.model.Person;
import com.hwadee.tradeUnion.service.PersonService;
import com.opensymphony.xwork2.ActionSupport; @Component("PersonAction")
public class PersonAction extends ActionSupport { /**
*
*/
private static final long serialVersionUID = 1L; private List<Person> personList; private PersonService personService;
private Person person;
private int id; public PersonService getPersonService() {
return personService;
} @Resource
public void setPersonService(PersonService personService) {
this.personService = personService;
} public String list() {
personList = personService.list(); return SUCCESS;
} public String add() {
personService.add(person); return SUCCESS;
}
public String update() {
personService.update(person);
return SUCCESS;
}
public String delete() { personService.deleteById(id);
return SUCCESS;
}
public String addInput() { return INPUT;
}
public String updateInput() {
this.person = this.personService.loadById(id);
return INPUT;
} public String load(){ this.person=this.personService.loadById(id); return SUCCESS;
} public List<Person> getPersonList() {
return personList;
} public void setPersonList(List<Person> personList) {
this.personList = personList;
} public Person getPerson() {
return person;
} public void setPerson(Person person) {
this.person = person;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} }
applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <context:annotation-config />
<context:component-scan base-package="com.hwadee" />
<!--
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="bjsxt" />
</bean>
--> <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> <bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--
<property name="annotatedClasses">
<list>
<value>com.bjsxt.model.User</value>
<value>com.bjsxt.model.Log</value>
</list>
</property>
-->
<property name="packagesToScan">
<list>
<value>com.hwadee.tradeUnion.model</value> </list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean> <!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>--> <bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <aop:config>
<aop:pointcut id="bussinessService"
expression="execution(public * com.hwadee.tradeUnion.service.*.*(..))" />
<aop:advisor pointcut-ref="bussinessService"
advice-ref="txAdvice" />
</aop:config> <tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!--<tx:method name="exists" read-only="true" /> -->
<tx:method name="list" read-only="true" />
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="loadById*" read-only="true"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="deleteById*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice> </beans>
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts Blank</display-name> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!--如果不定义webAppRootKey参数,那么webAppRootKey就是缺省的"webapp.root"--> <!-- <context-param> <param-name>webAppRootKey</param-name> <param-value>ssh.root</param-value> </context-param>--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param>
<!--配置log4j --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
<!-- default: /WEB-INF/applicationContext.xml -->
</listener> <context-param>
<param-name>contextConfigLocation</param-name>
<!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <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>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>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>
jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3300/TradeUnion
jdbc.username=root
jdbc.password=123456
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="hello">
<result>
/hello.jsp
</result>
</action>
<action name="*Login" class="{1}LoginAction">
<result name="success">/{1}/{1}-Manage.jsp</result>
<result name="fail">fail.jsp</result>
</action>
<action name="*-*-*" class="{2}Action" method="{3}">
<result name="success">/{1}/{2}-{3}.jsp</result>
<result name="input">/{1}/{2}-{3}.jsp</result>
<result name="fail">/{1}/{2}-{3}-fail.jsp</result>
</action>
</package>
<!-- Add packages here -->
</struts>
[置顶] struts2+hibernate+spring整合(annotation版)的更多相关文章
- Struts2+Hibernate+Spring 整合示例
转自:https://blog.csdn.net/tkd03072010/article/details/7468769 Struts2+Hibernate+Spring 整合示例 Spring整合S ...
- Struts2+Hibernate+Spring 整合示例[转]
原文 http://blog.csdn.net/tkd03072010/article/details/7468769 Spring整合Struts2.Hibernate原理概述: 从用户角度来看,用 ...
- Struts2 Spring Hibernate 框架整合 Annotation MavenProject
项目结构目录 pom.xml 添加和管理jar包 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns ...
- Spring+Struts2+Hibernate框架整合流程
一:基本步骤 新建Maven项目,导入相关依赖(推荐) 在WEB-INF的web.xml中进行配置 ————–Hibernate配置 —————- 创建entity包,创建数据库相关实体类 根据实体类 ...
- Spring+Struts2+Hibernate的整合
这篇主要采用Maven搭建Spring+Struts2+Hibernate的整合项目,复习一下SSH框架,虽然spring提供自己的MVC框架, 但是Spring也提供和其他框架的无缝整合,采用组件形 ...
- struts2+hibernate+spring简单整合且java.sql.SQLException: No suitable driver 问题解决
最近上j2ee的课,老师要求整合struts2+hibernate+spring,我自己其实早早地有准备弄的,现在都第9个项目了,无奈自己的思路和头绪把自己带坑了,当然也是经验问题,其实只是用myec ...
- 工作笔记3.手把手教你搭建SSH(struts2+hibernate+spring)环境
上文中我们介绍<工作笔记2.软件开发经常使用工具> 从今天開始本文将教大家怎样进行开发?本文以搭建SSH(struts2+hibernate+spring)框架为例,共分为3步: 1)3个 ...
- 二十六:Struts2 和 spring整合
二十六:Struts2 和 spring整合 将项目名称为day29_02_struts2Spring下的scr目录下的Struts.xml文件拷贝到新项目的scr目录下 在新项目的WebRoot-- ...
- 第一次做的struts2与spring整合
参考:http://www.cnblogs.com/S-E-P/archive/2012/01/18/2325253.html 这篇文章说的关键就是“除了导入Struts2和Spring的核心库之外, ...
随机推荐
- 如何将json拼接在url后面当做地址栏参数?
function param(data) { let url = '' for (var k in data) { let value = data[k] !== undefined ? data[k ...
- LoadRunner中进程运行和线程运行区别
LoadRunner中的进程与线程 1.进程与线程的区别: 进程和线程的区别是什么?进程和线程都是由操作系统所体会的程序运行的基本单元,系统利用该基本单元实现系统对应用的并发性.进程和线程的区别 ...
- 【剑指offer】面试题 49. 丑数
面试题 49. 丑数 题目描述 题目:把只包含因子2.3和5的数称作丑数(Ugly Number).例如6.8都是丑数,但14不是,因为它包含因子7. 习惯上我们把1当做是第一个丑数.求按从小到大的顺 ...
- POJ 2777 Count Color(线段树 + 染色问题)
传送门:Count Color Description Chosen Problem Solving and Program design as an optional course, you are ...
- SCU - 4439 Vertex Cover (图的最小点覆盖集)
Vertex Cover frog has a graph with \(n\) vertices \(v(1), v(2), \dots, v(n)\) and \(m\) edges \((v(a ...
- WebDAV服务漏洞利用工具DAVTest
WebDAV服务漏洞利用工具DAVTest WebDAV是基于Web服务的扩展服务.它允许用户像操作本地文件一样,操作服务器上的文件.借助该功能,用户很方便的在网络上存储自己的文件.为了方便用户使 ...
- Python - 字符和字符值之间的转换
字符和字符值之间的转换 Python中, 字符和字符值, 直接的转换, 包含ASCII码和字母之间的转换,Unicode码和数字之间的转换; 也可以使用map, 进行批量转换, 输出为集合, 使用jo ...
- xUtils 中的 BitmapUtils
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha xUtils框架,包括BitmapUtils.DbUtils.ViewUtils和Htt ...
- 【BZOJ 3924】【ZJOI 2015】幻想乡战略游戏
http://www.lydsy.com/JudgeOnline/problem.php?id=3924 gty的测试题,不会动态点分治而且看不出来链剖做法而且暴力打残所以这道题喜闻乐见的爆零了qwq ...
- 一次完整的HTTP请求的大致过程(转)
说明:这些理论基本都来自网上,所以不一定准确,但一定是比较好理解的,如果要刨根问底,最好的方式就是看书,且要看权威的书. 一次完整的HTTP请求所经历的7个步骤 HTTP通信机制是在一次完整的HTTP ...