ショッピングモールショップショップショップ連載(1)
6626 ワード
モジュール1の親
1.親インタフェース
1つのプロジェクトを作成する時、多くの重複コードの作成を避けることができなくて、プロジェクトを肥大化させないために、ここでよく使う方法を1つのインタフェースクラスに抽象化して、サブクラスに実現して、符号化の重複を減らす必要があります
/*** * * * * @param <T> */
public interface BaseDao<T> {
/*** * */
public void save(T entity);
/*** * */
public void delete(Long id);
/** * */
public void update(T entity);
/*** * */
public List<T> queryAll();
/*** * id */
public T getById(Long id);
}
2.親インタフェース実装クラス
インタフェースの作成が完了した後、直接使用することはできません.インタフェース実装クラスを書いて実装する必要があります.
/*** * * @author liuzehui * @param <T> */
@Transactional
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> implements BaseDao<T> {
@Autowired
// sessionFactory
protected SessionFactory sessionFactory;
private Class<T> clazz = null;
//
public BaseDaoImpl() {
ParameterizedType pt = (ParameterizedType) this.getClass()
.getGenericSuperclass();
clazz = (Class<T>) pt.getActualTypeArguments()[0];
System.out.println("------>clazz=" + clazz);
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
/*** * */
@Override
public void save(T entity) {
getSession().save(entity);
}
/*** * id */
@Override
public void delete(Long id) {
if (null != id && id > 0) {
Object obj = getById(id);
if (obj != null) {
getSession().delete(obj);
} else {
return;
}
} else {
return;
}
}
/*** * */
@Override
public void update(T entity) {
getSession().update(entity);
}
/*** * id */
@Override
public T getById(Long id) {
if (null != id && id > 0) {
Object obj = getSession().get(clazz, id);
return (T) obj;
} else {
return null;
}
}
/*** * */
@Override
public List<T> queryAll() {
List<T> list = getSession()
.createQuery("from " + clazz.getSimpleName()).list();
if (list != null && list.size() > 0) {
return list;
} else {
return Collections.EMPTY_LIST;
}
}
}
以降インタフェースはBaseDaoを継承し,インタフェース実装クラスはBaseDaoImplを継承してから独自のインタフェースを実現する.
3.親アクションの作成
@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
//
protected T model;
protected Class<T> clazz = null;
@SuppressWarnings("unchecked")
public BaseAction() {
try {
// T
ParameterizedType pt = (ParameterizedType) this.getClass()
.getGenericSuperclass();
clazz = (Class<T>) pt.getActualTypeArguments()[0];
// model
model = clazz.newInstance();
System.out.println("------->model:" + model);
} catch (Exception e) {
}
}
@Override
public T getModel() {
return (T) model;
}
}
以降、すべてのアクションがこの親を継承します.