ssh Dao與Service的設計與實現

來源:互聯網
上載者:User

標籤:style   blog   http   java   get   使用   

使用UML設計程式


使用 使用案例圖 畫出程式的功能模組(小人代表角色,橢圓代表功能)



第一步:畫出實體類的關聯關係

使用類圖設計程式(關鍵)

單向箭頭表示單向關聯,沒有箭頭表示雙向關聯,線的屬性(關聯屬性)

類的屬性和方法一般隱藏



第二步:Dao的設計與實現

BaseDao定義每個Dao都會使用到的通用介面<<Interface>>

BaseDaoImpl實現BaseDao的抽象類別(用斜體表示抽象,用虛線空心箭頭表示實現介面)

每一個實體類都會有一個Dao的實作類別(用實現空心箭頭表示繼承一個類,用虛線三角箭頭表示引用一個類)

BaseDao<T>

package com.atguigu.surveypark.dao;import java.util.List;/** * BaseDao介面 */public interface BaseDao<T> {//寫操作public void saveEntity(T t);public void saveOrUpdateEntity(T t);public void updateEntity(T t);public void deleteEntity(T t);public void batchEntityByHQL(String hql,Object...objects);//讀操作public T loadEntity(Integer id);public T getEntity(Integer id);public List<T> findEntityByHQL(String hql,Object...objects);}

BaseDaoImpl<T>

package com.atguigu.surveypark.dao.impl;import java.lang.reflect.ParameterizedType;import java.util.List;import javax.annotation.Resource;import org.hibernate.Query;import org.hibernate.SessionFactory;import com.atguigu.surveypark.dao.BaseDao;/** * 抽象的dao實現,專門用於繼承 */@SuppressWarnings("unchecked")public abstract class BaseDaoImpl<T> implements BaseDao<T> {//注入sessionFactory@Resourceprivate SessionFactory sf ;private Class<T> clazz ;public BaseDaoImpl(){//得到泛型話超類ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();clazz = (Class<T>) type.getActualTypeArguments()[0];}public void saveEntity(T t) {sf.getCurrentSession().save(t);}public void saveOrUpdateEntity(T t) {sf.getCurrentSession().saveOrUpdate(t);}public void updateEntity(T t) {sf.getCurrentSession().update(t);}public void deleteEntity(T t) {sf.getCurrentSession().delete(t);}/** * 按照HQL語句進行批次更新 */public void batchEntityByHQL(String hql, Object... objects) {Query q = sf.getCurrentSession().createQuery(hql);for(int i = 0 ; i < objects.length ; i ++){q.setParameter(i, objects[i]);}q.executeUpdate();}public T loadEntity(Integer id) {return (T) sf.getCurrentSession().load(clazz, id);}public T getEntity(Integer id) {return (T) sf.getCurrentSession().get(clazz, id);}public List<T> findEntityByHQL(String hql, Object... objects) {Query q = sf.getCurrentSession().createQuery(hql);for(int i = 0 ; i < objects.length ; i ++){q.setParameter(i, objects[i]);}return q.list();}}


第三步:Service設計與實現

分兩種情況:一種是單體Service(只操作一個Dao),一種是多體Service(操作多個Dao)

不是每一個Dao都有一個對應的Service

BaseService<T>:定義基本的介面,這個介面是所有的Service通用的

package com.atguigu.surveypark.service;import java.util.List;/** * 基本的dao介面 */public interface BaseService<T> {//寫操作public void saveEntity(T t);public void saveOrUpdateEntity(T t);public void updateEntity(T t);public void deleteEntity(T t);public void batchEntityByHQL(String hql,Object...objects);//讀操作public T loadEntity(Integer id);public T getEntity(Integer id);public List<T> findEntityByHQL(String hql,Object...objects);}

BaseServiceImpl<T>:實現基本的介面

package com.atguigu.surveypark.service.impl;import java.util.List;import javax.annotation.Resource;import com.atguigu.surveypark.dao.BaseDao;import com.atguigu.surveypark.service.BaseService;/** * 抽象的baseService,專門用於繼承 */public abstract class BaseServiceImpl<T> implements BaseService<T> {private BaseDao<T> dao ;//注入dao@Resourcepublic void setDao(BaseDao<T> dao) {this.dao = dao;}public void saveEntity(T t) {dao.saveEntity(t);}public void saveOrUpdateEntity(T t) {dao.saveOrUpdateEntity(t);}public void updateEntity(T t) {dao.updateEntity(t);}public void deleteEntity(T t) {dao.deleteEntity(t);}public void batchEntityByHQL(String hql, Object... objects) {dao.batchEntityByHQL(hql, objects);}public T loadEntity(Integer id) {return dao.loadEntity(id);}public T getEntity(Integer id) {return dao.getEntity(id);}public List<T> findEntityByHQL(String hql, Object... objects) {return dao.findEntityByHQL(hql, objects);}}


UserService:定義一個擴充介面,這個介面的方法特定義User這個實體類。這裡實現BaseServcie這個介面是為了面向介面編程。

package com.atguigu.surveypark.service;import com.atguigu.surveypark.model.User;/** * UserService */public interface UserService extends BaseService<User> {}


一個簡單的樣本:可以將UserServiceImpl類注入到BaseServcie這個介面,這樣就可以調用BaseServcie的基本方法和擴充方法了

注意:需要覆蓋父類的public void setDao(BaseDao<User> dao) {這個方法,因為@Resource先匹配名字再匹配類型,類型已經被BaseServiceImpl使用了一次,多個類使用同一個類型所以是不行的,覆蓋這個方法然後使用特定的名字的類的dao進行注入

package com.atguigu.surveypark.service.impl;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.atguigu.surveypark.dao.BaseDao;import com.atguigu.surveypark.model.User;import com.atguigu.surveypark.service.UserService;@Service("userService")public class UserServiceImpl extends BaseServiceImpl<User> implementsUserService {@Resource(name="userDao")public void setDao(BaseDao<User> dao) {super.setDao(dao);}}




第四步:action的設計與實現


BaseAction<T>

package com.atguigu.surveypark.struts2.action;import java.lang.reflect.ParameterizedType;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;import com.opensymphony.xwork2.Preparable;/** * 抽象action,專門用於繼承 */public abstract class BaseAction<T> extends ActionSupport implementsModelDriven<T>, Preparable {private static final long serialVersionUID = 9180917383072055589L;public T model ;public BaseAction(){try {ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();Class clazz = (Class) type.getActualTypeArguments()[0];model = (T) clazz.newInstance();} catch (Exception e) {e.printStackTrace();}}public void prepare() throws Exception {}public T getModel(){return model ;}}

一個簡單的例子

package com.atguigu.surveypark.struts2.action;import javax.annotation.Resource;import org.apache.struts2.interceptor.validation.SkipValidation;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import com.atguigu.surveypark.model.User;import com.atguigu.surveypark.service.UserService;import com.atguigu.surveypark.util.DataUtil;import com.atguigu.surveypark.util.ValidateUtil;/** * 註冊action */@Controller@Scope("prototype")public class RegAction extends BaseAction<User> {private static final long serialVersionUID = 7351588309970506225L;private String confirmPassword ;//注入userService@Resourceprivate UserService userService ;public String getConfirmPassword() {return confirmPassword;}public void setConfirmPassword(String confirmPassword) {this.confirmPassword = confirmPassword;}/** * 到達註冊頁面 */@SkipValidationpublic String toRegPage(){return "regPage" ;}/** * 進行使用者註冊 */public String doReg(){//密碼加密model.setPassword(DataUtil.md5(model.getPassword()));userService.saveEntity(model);return SUCCESS ;}/** * 校正 */public void validate() {//1.非空if(!ValidateUtil.isValid(model.getEmail())){addFieldError("email", "email是必填項!");}if(!ValidateUtil.isValid(model.getPassword())){addFieldError("password", "password是必填項!");}if(!ValidateUtil.isValid(model.getNickName())){addFieldError("nickName", "nickName是必填項!");}if(hasErrors()){return ;}//2.密碼一致性if(!model.getPassword().equals(confirmPassword)){addFieldError("password", "密碼不一致!");return  ;}//3.email佔用if(userService.isRegisted(model.getEmail())){addFieldError("email", "email已佔用!");}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.