步骤 1 : 先看委派重构实现之后的好处 步骤 2 : ServiceDelegateDAO 步骤 3 : ServiceDelegateDAO的快速生成技巧 步骤 4 : BaseServiceImpl继承ServiceDelegateDAO 步骤 5 : 关于save方法的返回类型 步骤 6 : 委派模式的好处 步骤 7 : 可运行项目
在此之前,访问数据库都需要通过dao.XXX()来进行。 而委派重构之后,数据库相关方法,不再需要通过dao,直接调用即可,代码看上去更简洁。
增值内容,请先登录
完整的SSH模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE,SSH一整套技术栈, 从无到有涵盖全部133个知识点,571个开发步骤, 充实SSH项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package com.how2java.tmall.service.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.how2java.tmall.dao.impl.DAOImpl;
import com.how2java.tmall.service.BaseService;
import com.how2java.tmall.util.Page;
@Service
public class BaseServiceImpl implements BaseService {
@Autowired DAOImpl dao;
protected Class clazz;
public static void main(String[] args) {
new CategoryServiceImpl().showClass();
}
public void showClass(){
System.out.println(clazz);
}
public BaseServiceImpl(){
try{
throw new Exception();
}
catch(Exception e){
StackTraceElement stes[]= e.getStackTrace();
String serviceImpleClassName= stes[1].getClassName();
try {
Class serviceImplClazz= Class.forName(serviceImpleClassName);
String serviceImpleClassSimpleName = serviceImplClazz.getSimpleName();
String pojoSimpleName = serviceImpleClassSimpleName.replaceAll("ServiceImpl", "");
String pojoPackageName = serviceImplClazz.getPackage().getName().replaceAll(".service.impl", ".pojo");
String pojoFullName = pojoPackageName +"."+ pojoSimpleName;
clazz=Class.forName(pojoFullName);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
@Override
public List list() {
DetachedCriteria dc = DetachedCriteria.forClass(clazz);
dc.addOrder(Order.desc("id"));
return dao.findByCriteria(dc);
}
@Override
public int total() {
String hql = "select count(*) from " + clazz.getName() ;
List<Long> l= dao.find(hql);
if(l.isEmpty())
return 0;
Long result= l.get(0);
return result.intValue();
}
@Override
public List<Object> listByPage(Page page) {
DetachedCriteria dc = DetachedCriteria.forClass(clazz);
dc.addOrder(Order.desc("id"));
return dao.findByCriteria(dc,page.getStart(),page.getCount());
}
@Override
public Integer save(Object object) {
return (Integer) dao.save(object);
}
@Override
public void delete(Object object) {
dao.delete(object);
}
@Override
public Object get(Class clazz, int id) {
return dao.get(clazz, id);
}
@Override
public void update(Object object) {
dao.update(object);
}
}
package com.how2java.tmall.service.impl;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Filter;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.LockMode;
import org.hibernate.ReplicationMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.how2java.tmall.dao.impl.DAOImpl;
public class ServiceDelegateDAO {
@Autowired DAOImpl dao;
public void delete(Object entity) throws DataAccessException {
dao.delete(entity);
}
public Serializable save(Object entity) throws DataAccessException {
return dao.save(entity);
}
public void afterPropertiesSet() {
dao.afterPropertiesSet();
}
public int bulkUpdate(String queryString, Object... values) throws DataAccessException {
return dao.bulkUpdate(queryString, values);
}
public int bulkUpdate(String queryString, Object value) throws DataAccessException {
return dao.bulkUpdate(queryString, value);
}
public int bulkUpdate(String queryString) throws DataAccessException {
return dao.bulkUpdate(queryString);
}
public void clear() throws DataAccessException {
dao.clear();
}
public void closeIterator(Iterator arg0) throws DataAccessException {
dao.closeIterator(arg0);
}
public boolean contains(Object entity) throws DataAccessException {
return dao.contains(entity);
}
public DataAccessException convertHibernateAccessException(HibernateException ex) {
return dao.convertHibernateAccessException(ex);
}
public void delete(Object entity, LockMode lockMode) throws DataAccessException {
dao.delete(entity, lockMode);
}
public void delete(String entityName, Object entity, LockMode lockMode) throws DataAccessException {
dao.delete(entityName, entity, lockMode);
}
public void delete(String entityName, Object entity) throws DataAccessException {
dao.delete(entityName, entity);
}
public void deleteAll(Collection entities) throws DataAccessException {
dao.deleteAll(entities);
}
public Filter enableFilter(String filterName) throws IllegalStateException {
return dao.enableFilter(filterName);
}
public boolean equals(Object obj) {
return dao.equals(obj);
}
public void evict(Object entity) throws DataAccessException {
dao.evict(entity);
}
public <T> T execute(HibernateCallback<T> action) throws DataAccessException {
return dao.execute(action);
}
public List executeFind(HibernateCallback<?> action) throws DataAccessException {
return dao.executeFind(action);
}
public <T> T executeWithNativeSession(HibernateCallback<T> action) {
return dao.executeWithNativeSession(action);
}
public <T> T executeWithNewSession(HibernateCallback<T> action) {
return dao.executeWithNewSession(action);
}
public List find(String queryString, Object... values) throws DataAccessException {
return dao.find(queryString, values);
}
public List find(String queryString, Object value) throws DataAccessException {
return dao.find(queryString, value);
}
public List find(String queryString) throws DataAccessException {
return dao.find(queryString);
}
public List findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults) throws DataAccessException {
return dao.findByCriteria(criteria, firstResult, maxResults);
}
public List findByCriteria(DetachedCriteria criteria) throws DataAccessException {
return dao.findByCriteria(criteria);
}
public List findByExample(Object exampleEntity, int firstResult, int maxResults) throws DataAccessException {
return dao.findByExample(exampleEntity, firstResult, maxResults);
}
public List findByExample(Object exampleEntity) throws DataAccessException {
return dao.findByExample(exampleEntity);
}
public List findByExample(String entityName, Object exampleEntity, int firstResult, int maxResults)
throws DataAccessException {
return dao.findByExample(entityName, exampleEntity, firstResult, maxResults);
}
public List findByExample(String entityName, Object exampleEntity) throws DataAccessException {
return dao.findByExample(entityName, exampleEntity);
}
public List findByNamedParam(String queryString, String paramName, Object value) throws DataAccessException {
return dao.findByNamedParam(queryString, paramName, value);
}
public List findByNamedParam(String queryString, String[] paramNames, Object[] values) throws DataAccessException {
return dao.findByNamedParam(queryString, paramNames, values);
}
public List findByNamedQuery(String queryName, Object... values) throws DataAccessException {
return dao.findByNamedQuery(queryName, values);
}
public List findByNamedQuery(String queryName, Object value) throws DataAccessException {
return dao.findByNamedQuery(queryName, value);
}
public List findByNamedQuery(String queryName) throws DataAccessException {
return dao.findByNamedQuery(queryName);
}
public List findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)
throws DataAccessException {
return dao.findByNamedQueryAndNamedParam(queryName, paramName, value);
}
public List findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values)
throws DataAccessException {
return dao.findByNamedQueryAndNamedParam(queryName, paramNames, values);
}
public List findByNamedQueryAndValueBean(String queryName, Object valueBean) throws DataAccessException {
return dao.findByNamedQueryAndValueBean(queryName, valueBean);
}
public List findByValueBean(String queryString, Object valueBean) throws DataAccessException {
return dao.findByValueBean(queryString, valueBean);
}
public void flush() throws DataAccessException {
dao.flush();
}
public <T> T get(Class<T> entityClass, Serializable id, LockMode lockMode) throws DataAccessException {
return dao.get(entityClass, id, lockMode);
}
public <T> T get(Class<T> entityClass, Serializable id) throws DataAccessException {
return dao.get(entityClass, id);
}
public Object get(String entityName, Serializable id, LockMode lockMode) throws DataAccessException {
return dao.get(entityName, id, lockMode);
}
public Object get(String entityName, Serializable id) throws DataAccessException {
return dao.get(entityName, id);
}
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
return dao.getEntityInterceptor();
}
public int getFetchSize() {
return dao.getFetchSize();
}
public String[] getFilterNames() {
return dao.getFilterNames();
}
public int getFlushMode() {
return dao.getFlushMode();
}
public SQLExceptionTranslator getJdbcExceptionTranslator() {
return dao.getJdbcExceptionTranslator();
}
public int getMaxResults() {
return dao.getMaxResults();
}
public String getQueryCacheRegion() {
return dao.getQueryCacheRegion();
}
public SessionFactory getSessionFactory() {
return dao.getSessionFactory();
}
public int hashCode() {
return dao.hashCode();
}
public void initialize(Object arg0) throws DataAccessException {
dao.initialize(arg0);
}
public boolean isAllowCreate() {
return dao.isAllowCreate();
}
public boolean isAlwaysUseNewSession() {
return dao.isAlwaysUseNewSession();
}
public boolean isCacheQueries() {
return dao.isCacheQueries();
}
public boolean isCheckWriteOperations() {
return dao.isCheckWriteOperations();
}
public boolean isExposeNativeSession() {
return dao.isExposeNativeSession();
}
public Iterator iterate(String queryString, Object... values) throws DataAccessException {
return dao.iterate(queryString, values);
}
public Iterator iterate(String queryString, Object value) throws DataAccessException {
return dao.iterate(queryString, value);
}
public Iterator iterate(String queryString) throws DataAccessException {
return dao.iterate(queryString);
}
public <T> T load(Class<T> entityClass, Serializable id, LockMode lockMode) throws DataAccessException {
return dao.load(entityClass, id, lockMode);
}
public <T> T load(Class<T> entityClass, Serializable id) throws DataAccessException {
return dao.load(entityClass, id);
}
public void load(Object entity, Serializable id) throws DataAccessException {
dao.load(entity, id);
}
public Object load(String entityName, Serializable id, LockMode lockMode) throws DataAccessException {
return dao.load(entityName, id, lockMode);
}
public Object load(String entityName, Serializable id) throws DataAccessException {
return dao.load(entityName, id);
}
public <T> List<T> loadAll(Class<T> entityClass) throws DataAccessException {
return dao.loadAll(entityClass);
}
public void lock(Object entity, LockMode lockMode) throws DataAccessException {
dao.lock(entity, lockMode);
}
public void lock(String entityName, Object entity, LockMode lockMode) throws DataAccessException {
dao.lock(entityName, entity, lockMode);
}
public <T> T merge(String entityName, T entity) throws DataAccessException {
return dao.merge(entityName, entity);
}
public <T> T merge(T entity) throws DataAccessException {
return dao.merge(entity);
}
public void persist(Object entity) throws DataAccessException {
dao.persist(entity);
}
public void persist(String entityName, Object entity) throws DataAccessException {
dao.persist(entityName, entity);
}
public void refresh(Object entity, LockMode lockMode) throws DataAccessException {
dao.refresh(entity, lockMode);
}
public void refresh(Object entity) throws DataAccessException {
dao.refresh(entity);
}
public void replicate(Object entity, ReplicationMode replicationMode) throws DataAccessException {
dao.replicate(entity, replicationMode);
}
public void replicate(String entityName, Object entity, ReplicationMode replicationMode)
throws DataAccessException {
dao.replicate(entityName, entity, replicationMode);
}
public Serializable save(String entityName, Object entity) throws DataAccessException {
return dao.save(entityName, entity);
}
public void saveOrUpdate(Object entity) throws DataAccessException {
dao.saveOrUpdate(entity);
}
public void saveOrUpdate(String entityName, Object entity) throws DataAccessException {
dao.saveOrUpdate(entityName, entity);
}
public void saveOrUpdateAll(Collection entities) throws DataAccessException {
dao.saveOrUpdateAll(entities);
}
public void setAllowCreate(boolean allowCreate) {
dao.setAllowCreate(allowCreate);
}
public void setAlwaysUseNewSession(boolean alwaysUseNewSession) {
dao.setAlwaysUseNewSession(alwaysUseNewSession);
}
public void setBeanFactory(BeanFactory beanFactory) {
dao.setBeanFactory(beanFactory);
}
public void setCacheQueries(boolean cacheQueries) {
dao.setCacheQueries(cacheQueries);
}
public void setCheckWriteOperations(boolean checkWriteOperations) {
dao.setCheckWriteOperations(checkWriteOperations);
}
public void setEntityInterceptor(Interceptor entityInterceptor) {
dao.setEntityInterceptor(entityInterceptor);
}
public void setEntityInterceptorBeanName(String entityInterceptorBeanName) {
dao.setEntityInterceptorBeanName(entityInterceptorBeanName);
}
public void setExposeNativeSession(boolean exposeNativeSession) {
dao.setExposeNativeSession(exposeNativeSession);
}
public void setFetchSize(int fetchSize) {
dao.setFetchSize(fetchSize);
}
public void setFilterName(String filter) {
dao.setFilterName(filter);
}
public void setFilterNames(String[] filterNames) {
dao.setFilterNames(filterNames);
}
public void setFlushMode(int flushMode) {
dao.setFlushMode(flushMode);
}
public void setFlushModeName(String constantName) {
dao.setFlushModeName(constantName);
}
public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) {
dao.setJdbcExceptionTranslator(jdbcExceptionTranslator);
}
public void setMaxResults(int maxResults) {
dao.setMaxResults(maxResults);
}
public void setQueryCacheRegion(String queryCacheRegion) {
dao.setQueryCacheRegion(queryCacheRegion);
}
public void setSessionFactory(SessionFactory sessionFactory) {
dao.setSessionFactory(sessionFactory);
}
public String toString() {
return dao.toString();
}
public void update(Object entity, LockMode lockMode) throws DataAccessException {
dao.update(entity, lockMode);
}
public void update(Object entity) throws DataAccessException {
dao.update(entity);
}
public void update(String entityName, Object entity, LockMode lockMode) throws DataAccessException {
dao.update(entityName, entity, lockMode);
}
public void update(String entityName, Object entity) throws DataAccessException {
dao.update(entityName, entity);
}
}
增值内容,请先登录
完整的SSH模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE,SSH一整套技术栈, 从无到有涵盖全部133个知识点,571个开发步骤, 充实SSH项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package com.how2java.tmall.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.how2java.tmall.dao.impl.DAOImpl;
public class ServiceDelegateDAO {
@Autowired
DAOImpl dao;
}
package com.how2java.tmall.service.impl; import org.springframework.beans.factory.annotation.Autowired; import com.how2java.tmall.dao.impl.DAOImpl; public class ServiceDelegateDAO { @Autowired DAOImpl dao; }
增值内容,请先登录
完整的SSH模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE,SSH一整套技术栈, 从无到有涵盖全部133个知识点,571个开发步骤, 充实SSH项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package com.how2java.tmall.service.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Service;
import com.how2java.tmall.service.BaseService;
import com.how2java.tmall.util.Page;
@Service
public class BaseServiceImpl extends ServiceDelegateDAO implements BaseService {
protected Class clazz;
public BaseServiceImpl(){
try{
throw new Exception();
}
catch(Exception e){
StackTraceElement stes[]= e.getStackTrace();
String serviceImpleClassName= stes[1].getClassName();
try {
Class serviceImplClazz= Class.forName(serviceImpleClassName);
String serviceImpleClassSimpleName = serviceImplClazz.getSimpleName();
String pojoSimpleName = serviceImpleClassSimpleName.replaceAll("ServiceImpl", "");
String pojoPackageName = serviceImplClazz.getPackage().getName().replaceAll(".service.impl", ".pojo");
String pojoFullName = pojoPackageName +"."+ pojoSimpleName;
clazz=Class.forName(pojoFullName);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
@Override
public List list() {
DetachedCriteria dc = DetachedCriteria.forClass(clazz);
dc.addOrder(Order.desc("id"));
return findByCriteria(dc);
}
@Override
public int total() {
String hql = "select count(*) from " + clazz.getName() ;
List<Long> l= find(hql);
if(l.isEmpty())
return 0;
Long result= l.get(0);
return result.intValue();
}
@Override
public List<Object> listByPage(Page page) {
DetachedCriteria dc = DetachedCriteria.forClass(clazz);
dc.addOrder(Order.desc("id"));
return findByCriteria(dc,page.getStart(),page.getCount());
}
@Override
public Integer save(Object object) {
return (Integer) super.save(object);
}
@Override
public Object get(Class clazz, int id) {
return super.get(clazz, id);
}
@Override
public Object get(int id) {
return get(clazz, id);
}
// 因为继承了ServiceDelegateDAO,所以就继承了update和delete方法
// public void update(Object object) {
// update(object);
// }
// public void delete(Object object) {
// delete(object);
// }
}
增值内容,请先登录
完整的SSH模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE,SSH一整套技术栈, 从无到有涵盖全部133个知识点,571个开发步骤, 充实SSH项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
1. 通过委派模式把dao隐藏起来,调用的时候意识不到dao的存在,代码看起来更加简洁
2. 通过继承委派模式的ServiceDelegateDAO,继承了update和delete,直接使用即可,BaseServiceImpl 类无须再额外提供这两个方法
增值内容,请先登录
完整的SSH模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE,SSH一整套技术栈, 从无到有涵盖全部133个知识点,571个开发步骤, 充实SSH项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
问答区域
2020-04-07
我们必须重写save方法吗
3 个答案
how2j 跳转到问题位置 答案时间:2020-04-09 方法重写的时候,不能仅仅修改返回类型。
比如有两个方法,一个是
int save()
一个是
long save()
他们是不能共存的,了解一下?
xuao 跳转到问题位置 答案时间:2020-04-08
我知道必须实现BaseService接口中的save方法,但是如果将BaseService中的save方法改成这样呢
public Serializable save(Object object);
那么在BaseServiceImpl 中继承的104个方法里已经有一个方法实现了BaseService接口中的save方法了,这样不就省事了吗。
how2j 跳转到问题位置 答案时间:2020-04-08 首先BaseService是接口,不是类,所以 BaseServiceImpl 的 save 方法不叫做继承,而叫做实现。
BaseServiceImpl 作为 BaseService的实现类,必须实现其声明的方法,与这个方法的返回类型无关。
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2019-05-27
站长有两个疑问?麻烦帮忙解答一下。
1 个答案
how2j 跳转到问题位置 答案时间:2019-05-28 1. 因为不加个 super. 不就是自己调用自己,无限死循环了嘛
2. 重写 get, 是为了不用再手动传 class 进去了,更方便嘛
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2018-06-04
为什么不直接继承 DAOImpl 而继承 ServiceDelegateDAO ,继承DAOImpl 会出错吗?
2017-10-10
步骤四打错了
2017-09-13
为什么BaseService接口不直接去掉save方法
提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 1 条以前的提问,请 点击查看
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|