基于注解的SSH的发射泛型的MVC设计模式
来源:互联网 发布:网络控制室设备 编辑:程序博客网 时间:2024/06/06 03:21
公共的dao接口
package com.zeng.ping.dao;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.zeng.ping.util.PageInfo;
/**
* 公共的接口实现对所有的类的数据库操作
* @author
*
* @param <T>
*/
public interface ICommonDao<T>
{
/**
* 保存
* @param entity
*/
void save(T entity);
/**
* 条件查询
* @param condition
* @param params
* @param orderby
* @return
*/
List<T> findCollectionByConditionNoPage(String condition,Object[] params, Map<String, String> orderby);
List<T> findCollectionByConditionNoPageWithCache(String condition, Object[] params, Map<String, String> orderby);
/**
* 跟新
* @param entity
*/
void update(T entity);
/**
* 通过id查询
* @param id
* @return
*/
T getEntityById(Serializable id);
/**
* 根据集合删除
* @param list
*/
void deleteObjectsByCollection(List<T> list);
/**
* 根据多个id批量删除
* @param ids
*/
void deleteObjectsByIds(Serializable...ids);
List<T> findCollectionByConditionWithPage(String condition,Object[] params, Map<String, String> orderby, PageInfo pageInfo);
List findCollectionByConditionNoPageBySelectCondtion(String condition,Object[] params, Map<String, String> orderby, String selectCondition);
void saveEntityList(List<T> entitys);
}
公共dao实现
package com.zeng.ping.dao.impl;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
泛型的工具类
package com.zeng.ping.util;
import java.lang.reflect.ParameterizedType;
public class TUtils
{
public static Class<?> getTGenericSuperclass(Class<?> clz)
{
ParameterizedType type = (ParameterizedType)clz.getGenericSuperclass();
return (Class<?>)type.getActualTypeArguments()[0];
}
}
import com.zeng.ping.dao.ICommonDao;
import com.zeng.ping.util.PageInfo;
import com.zeng.ping.util.TUtils;
public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T>
{
//获得T的具体类型的class文件
private Class entityClass = TUtils.getTGenericSuperclass(this.getClass());
@Resource(name = "sessionFactory")
public final void setSessionFactoryDi(SessionFactory sessionFactory)
{
this.setSessionFactory(sessionFactory);
}
/* 保存 */
public void save(T entity)
{
this.getHibernateTemplate().save(entity);
}
// 根据条件查询,不使用二级缓存
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findCollectionByConditionNoPage(String condition,
final Object[] params, Map<String, String> orderby)
{
String hql = "from " + entityClass.getSimpleName() + " e where 1=1 ";
String orders = makeOrderBy(orderby);
final String finalHql = hql + condition + orders;
// return this.getHibernateTemplate().find(finalHql, params);
List<T> list = this.getHibernateTemplate().execute(
new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(finalHql);
if (null != params && params.length > 0)
{
for (int i = 0; i < params.length; i++)
{
query.setParameter(i, params[i]);
}
}
return query.list();
}
});
return list;
}
// 根据条件查询使用二级缓存
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findCollectionByConditionNoPageWithCache(String condition,
final Object[] params, Map<String, String> orderby)
{
String hql = "from " + entityClass.getSimpleName() + " e where 1=1 ";
String orders = makeOrderBy(orderby);
final String finalHql = hql + condition + orders;
// return this.getHibernateTemplate().find(finalHql, params);
List<T> list = this.getHibernateTemplate().execute(
new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(finalHql);
if (null != params && params.length > 0)
{
for (int i = 0; i < params.length; i++)
{
query.setParameter(i, params[i]);
}
}
query.setCacheable(true);
return query.list();
}
});
return list;
}
/**指定查询条件,查询结果集(不分页),使用投影查询的方式查询*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findCollectionByConditionNoPageBySelectCondtion(String condition,final Object[] params, Map<String, String> orderby, String selectCondition)
{
String hql = "select " + selectCondition + " from " + entityClass.getSimpleName() + " e where 1=1 ";
String orders = makeOrderBy(orderby);
final String finalHql = hql + condition + orders;
// return this.getHibernateTemplate().find(finalHql, params);
List<T> list = this.getHibernateTemplate().execute(
new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(finalHql);
if (null != params && params.length > 0)
{
for (int i = 0; i < params.length; i++)
{
query.setParameter(i, params[i]);
}
}
return query.list();
}
});
return list;
}
// 组织排序条件
private String makeOrderBy(Map<String, String> orderby)
{
StringBuilder builder = new StringBuilder("");
if (null != orderby && 0 < orderby.size())
{
builder.append(" order by ");
for (Map.Entry<String, String> entry : orderby.entrySet())
{
builder.append(entry.getKey() + " " + entry.getValue() + ",");
}
// 删除最后一个逗号
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
public void update(T entity)
{
this.getHibernateTemplate().update(entity);
}
@SuppressWarnings("unchecked")
// 根据id删除
public T getEntityById(Serializable id)
{
return (T) this.getHibernateTemplate().get(entityClass, id);
}
// 根据集合删除
public void deleteObjectsByCollection(List<T> list)
{
this.getHibernateTemplate().deleteAll(list);
}
// 根据数组删除
public void deleteObjectsByIds(Serializable... ids)
{
for (Serializable id : ids)
{
this.getHibernateTemplate().delete(getEntityById(id));
}
}
// 根据条件查询使用二级缓存
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findCollectionByConditionWithPage(String condition,
final Object[] params, Map<String, String> orderby,
final PageInfo pageInfo)
{
String hql = "from " + entityClass.getSimpleName() + " e where 1=1 ";
String orders = makeOrderBy(orderby);
final String finalHql = hql + condition + orders;
// return this.getHibernateTemplate().find(finalHql, params);
List<T> list = this.getHibernateTemplate().execute(
new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(finalHql);
if (null != params && params.length > 0)
{
for (int i = 0; i < params.length; i++)
{
query.setParameter(i, params[i]);
}
}
//分页开始
//设置总的记录数
pageInfo.setTotalResult(query.list().size());
//设置开始检索结果集位置
query.setFirstResult(pageInfo.getBeginResult());
//每页显示的最大记录数
query.setMaxResults(pageInfo.getPageSize());
//开启二级缓存
query.setCacheable(true);
return query.list();
}
});
return list;
}
public void saveEntityList(List<T> entitys)
{
getHibernateTemplate().saveOrUpdateAll(entitys);
}
}
//service接口
package com.zeng.ping.service;
import java.io.Serializable;
import java.util.List;
import com.zeng.ping.domain.ElecText;
public interface IElecTextService
{
public static final String SERVICE_NAME = "com.zeng.ping.service.impl.ElecTextServiceImpl";
void save(ElecText entity);
/**
* 条件查询,没有分页
* @param entity
* @return
*/
List<ElecText> findCollectionByConditionNoPage(ElecText entity);
/**
* 跟新
* @param entity
*/
void update(ElecText entity);
/**
* 根据id删除
* @param id
* @return
*/
ElecText getEntityById(Serializable id);
/**
* 根据集合删除
* @param list
*/
void deleteObjectsByCollection(List<ElecText> list);
/**
* 根据ids删除
* @param ids
*/
void deleteObjectsByIds(Serializable...ids);
}
//测试service实现类
package com.zeng.ping.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
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.zeng.ping.dao.IElecTextDao;
import com.zeng.ping.domain.ElecText;
import com.zeng.ping.service.IElecTextService;
@Service(IElecTextService.SERVICE_NAME)
@Transactional(readOnly=true)
public class ElecTextServiceImpl implements IElecTextService
{
@Resource(name=IElecTextDao.DAO_NAME)
private IElecTextDao elecTextDao;
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public void save(ElecText entity)
{
elecTextDao.save(entity);
}
public List<ElecText> findCollectionByConditionNoPage(ElecText entity)
{
String condition = "";
List<Object> list = new ArrayList<Object>();
if(StringUtils.isNotBlank(entity.getTextName()))
{
condition += " and e.textName like ?";
list.add("%" + entity.getTextName() + "%");
}
if(StringUtils.isNotBlank(entity.getTextRemark()))
{
condition += " and e.textRemark like ?";
list.add("%" + entity.getTextRemark() + "%");
}
Object[] params = list.toArray();
Map<String, String> orderby = new LinkedHashMap<String, String>();
orderby.put("e.textDate", "asc");
orderby.put("e.textRemark", "desc");
return elecTextDao.findCollectionByConditionNoPage(condition, params, orderby);
}
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public void update(ElecText entity)
{
elecTextDao.update(entity);
}
public ElecText getEntityById(Serializable id)
{
return elecTextDao.getEntityById(id);
}
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public void deleteObjectsByCollection(List<ElecText> list)
{
elecTextDao.deleteObjectsByCollection(list);
}
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public void deleteObjectsByIds(Serializable...ids)
{
elecTextDao.deleteObjectsByIds(ids);
}
}
//通用action
package com.zeng.ping.web.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.zeng.ping.util.TUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
* 将action的基本功能封装在此类中
* @author zengping
*
* @param <T>
*/
@SuppressWarnings("serial")
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>, ServletRequestAware, ServletResponseAware
{
private T entity;
protected HttpServletRequest request;
protected HttpServletResponse response;
//创建T的真实实例
@SuppressWarnings("unchecked")
public BaseAction()
{
try
{
//得到真实类的字节码
Class<?> clz = TUtils.getTGenericSuperclass(this.getClass());
//创建真实类的实例
entity = (T) clz.newInstance();
} catch (Exception e)
{
e.printStackTrace();
}
}
//得到模型驱动
public T getModel()
{
return entity;
}
//初始化response
public void setServletResponse(HttpServletResponse response)
{
this.response = response;
}
//初始化request
public void setServletRequest(HttpServletRequest request)
{
this.request = request;
}
}
//实际action
package com.zeng.ping.web.action;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.zeng.ping.service.IElecTextService;
import com.zeng.ping.domain.ElecText;
@SuppressWarnings("serial")
@Controller("elecTextAction")
@Scope("prototype")
public class ElecTextAction extends BaseAction<ElecText>
{
@Resource(name=IElecTextService.SERVICE_NAME)
private IElecTextService elecTextService;
public ElecText elecText = this.getModel();
/**
* 保存
* @return
*/
public String save()
{
elecTextService.save(elecText);
return "save";
}
}
//domain 文件
package com.zeng.ping.domain;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class ElecText implements Serializable
{
private String textID;
private String textName;
private Date textDate;
private String textRemark;
public String getTextID()
{
return textID;
}
public void setTextID(String textID)
{
this.textID = textID;
}
public String getTextName()
{
return textName;
}
public void setTextName(String textName)
{
this.textName = textName;
}
public Date getTextDate()
{
return textDate;
}
public void setTextDate(Date textDate)
{
this.textDate = textDate;
}
public String getTextRemark()
{
return textRemark;
}
public void setTextRemark(String textRemark)
{
this.textRemark = textRemark;
}
@Override
public String toString()
{
return "ElecText [textID=" + textID + ", textName=" + textName
+ ", textDate=" + textDate + ", textRemark=" + textRemark + "]";
}
}
//持久化类映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zeng.ping.domain">
<class name="ElecText" table="elec_text">
<id name="textID" type="string" column="textID">
<generator class="uuid"></generator>
</id>
<property name="textName" type="string" column="textName"></property>
<property name="textDate" type="date" column="textDate"></property>
<property name="textRemark" type="string" column="textRemark"></property>
</class>
</hibernate-mapping>
spring配置文件
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.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">
<!-- 1:注解方式,配置组件的自动扫描 -->
<context:component-scan base-package="com.zeng.ping"/>
<!-- 2:? -->
<!-- 3:创建SessionFactory对象,这是spring整合hibernate的核心 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>
classpath:hibernate.cfg.xml
</value>
</property>
</bean>
<!-- 4:创建事务管理器 -->
<bean id="trManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 5:使用注解的方式管理事务,在业务层的类上和方法上,添加@Transcational -->
<tx:annotation-driven transaction-manager="trManager"/>
<!-- 配置文件
<tx:advice id="aa" transaction-manager="trManager">
<tx:attributes>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.zeng.ping.service..*.*(..))" id="bb"/>
<aop:advisor advice-ref="aa" pointcut-ref="bb"/>
</aop:config>
-->
</beans>
hibernate.cfg.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 连接数据库的信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/zengping?useUnicode=true&characterEncoding=utf8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 让hibernate自动提交事务
<property name="hibernate.connection.autocommit">true</property> -->
<!-- 其它配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<!-- 添加映射文件 -->
<mapping resource="com/zeng/ping/domain/ElecText.hbm.xml"/>
</session-factory>
</hibernate-configuration>
struts.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 设置struts2为开发模式:优点,修改struts.xml和资源文件的时候,不需要重启,同时在控制台输出错误信息 -->
<constant name="struts.devMode" value="true"></constant>
<!-- 设置struts2的开发主题,简单主题:优点,去掉struts2提供的样式 -->
<constant name="struts.ui.theme" value="simple"></constant>
<!-- 改变struts2的访问url的后缀名,为.do -->
<constant name="struts.action.extension" value="do"></constant>
<!-- 系统管理 -->
<package name="system" namespace="/system" extends="struts-default">
<action name="elecTextAction_*" class="elecTextAction" method="{1}">
<result name="save">/system/textAdd.jsp</result>
</action>
</package>
</struts>
log4j日志配置文件
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=error, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
web.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- 添加struts2的过滤器,这是struts2运行的核心 -->
<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容器启动的时候,自动加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
- 基于注解的SSH的发射泛型的MVC设计模式
- 基于注解的SSH
- 基于Servlet的MVC设计模式
- 设计模式:基于javabean的 MVC
- 基于spring注解的MVC
- 基于注解的Spring MVC
- 基于注解的spring mvc
- SSH三大框架与MVC设计模式的理解
- Java三大框架SSH与MVC的设计模式
- 浅谈MVC设计模式和SSH框架的关系
- 基于全注解的SSH简单框架
- 基于全注解的SSH简单框架
- 基于全注解方式的SSH框架
- 基于注解的SSH架构整合之一
- 基于注解的 Spring MVC 简单入门
- 基于注解的 Spring MVC 简单入门
- Spring MVC基于注解的Control
- 基于注解的 Spring MVC 简单入门
- jquery 学习日记3-几个容易弄混的事件
- android设置默认输入法
- Axis,axis2,Xfire以及cxf对比
- CSS入门三
- poj 1326 (jobdu 1484)输入问题
- 基于注解的SSH的发射泛型的MVC设计模式
- 注册表操作(VC_Win32)
- 从原理分析审批流表单配置功能使用的问题
- java编码的综合问题
- 家用游戏机的危机
- 解决vs2008工程右击不能正常显示工程属性页
- 一个数据库中将一个表中的数据导入另一个表中
- 线程取消(pthread_cancel)
- [转载]Oracle如何配置监听