[置顶] 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的核心库之外, ...
随机推荐
- PHP读取文件夹的文件列表
/** * getDir()取文件夹列表,getFile()取对应文件夹下面的文件列表,二者的区别在于判断有没有“.”后缀的文件,其他都一样 */ //获取文件目录列表,该方法返回数组 functio ...
- BZOJ 1901: Zju2112 Dynamic Rankings 区间k大 带修改 在线 线段树套平衡树
之前写线段树套splay数组版..写了6.2k..然后弃疗了.现在发现还是很水的..嘎嘎.. zju过不了,超时. upd:才发现zju是多组数据..TLE一版才发现.然后改了,MLE...手写内存池 ...
- pc、移动端H5网站 QQ在线客服、群链接代码【我和qq客服的那些事儿】
转载:http://blog.csdn.net/fungleo/article/details/51835368#comments 移动端H5 QQ在线客服链接代码 <a href=" ...
- 转:智能模糊测试工具 Winafl 的使用与分析
本文为 椒图科技 授权嘶吼发布,如若转载,请注明来源于嘶吼: http://www.4hou.com/technology/2800.html 注意: 函数的偏移地址计算方式是以IDA中出现的Imag ...
- 234. Palindrome Linked List【Easy】【判断链表是否回文】
Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ...
- [BZOJ5248][九省联考2018]一双木棋(连通性DP,对抗搜索)
5248: [2018多省省队联测]一双木棋 Time Limit: 20 Sec Memory Limit: 512 MBSubmit: 43 Solved: 34[Submit][Status ...
- [Codeforces-div.1 167B] Wizards and Huge Prize
[Codeforces-div.1 167B] Wizards and Huge Prize 试题分析 注意到每个物品互相独立,互不干扰之后就非常好做了. 算出一个物品最后的价值期望,然后乘以K即可. ...
- 【POJ】1089Intervals
Intervals Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8276 Accepted: 3270 Descrip ...
- BZOJ 3790 神奇项链(manacher+DP+树状数组)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3790 [题目大意] 问最少用几个回文串可以构成给出串,重叠部分可以合并 [题解] 我们 ...
- 【动态规划+高精度】mr360-定长不下降子序列
[题目大意] 韵哲君发现自己的面前有一行数字,当她正在琢磨应该干什么的时候,这时候,陈凡老师从天而降,走到了韵哲君的身边,低下头,对她耳语了几句,然后飘然而去. 陈凡老师说了什么呢,陈凡老师对韵哲君说 ...