我只想评论一下我从几十个关于通用DAO设计模式的样本中学到的东西。我在POJO类,DAO接口和DAO实现之间添加了继承层次结构,请参阅下面的代码
图例:
DAO(从家长到儿童)
DAO实施(从家长到儿童)
POJO课程(从家长到儿童)
数据访问对象(接口)
GenericDAO界面
public interface GenericDAO<T> {
... some crud operations common to all objets
}
PersonDAO界面
public interface PersonDAO<T extends Person> extends GenericDAO<T> {
... some operations unique to a person
}
StudentDAO界面
public interface StudentDAO extends PersonDAO<Student> {
... some operations unique to a student
}
实施
GenericDAO实施
@Repository("genericDAO")
public class GenericDAOImpl<T extends Person> implements GenericDAO<T> {
private Class<T> type;
@SuppressWarnings("unchecked")
public GenericDAOImpl() {
this.type = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), GenericDAO.class);
System.out.println(type);
}
@Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
@Transactional
@Override
public Integer save(T entity) {
return (Integer) sessionFactory.getCurrentSession().save(entity);
}
@SuppressWarnings("unchecked")
@Transactional
@Override
public T get(Integer id) {
return (T) sessionFactory.getCurrentSession().get(type, id);
}
}
PersonDAO实施
@Repository ("personDAO")
public class PersonDAOImpl<T extends Person> extends GenericDAOImpl<T> implements PersonDAO<T> {
.. implemented methods for person
}
StudentDAO实施
@Repository("studentDAO")
public class StudentDAOImpl extends PersonDAOImpl<Student> implements StudentDAO {
.. implemented methods for student
}
POJO课程(Hibernate Annotated)
人类(父抽象类)
@MappedSuperclass
public abstract class Person {
@Id
@GeneratedValue
@Column (name = "id")
private int id;
@Column (name = "name")
private String name;
@Column (name = "age")
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
具体课程(学生)
@Entity
@Table(name = "STUDENT")
public class Student extends Person {
@Column(name = "school")
private String school;
public Student() {
}
public Student(String school) {
this.school = school;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
我一直在考虑如何在POJO和DAO对象之间构建设计模式好几天,直到我根据我从中学到的一切来设计这些设计网络上的不同资源。我已经提出了基于POJO继承的DAO和DAO实现继承的想法。
我对任何建议或更正持开放态度。先感谢您!!!
答案 0 :(得分:1)
不是对设计的评论,但是......你考虑使用Spring Spring Data Jpa,它允许你:
编写存储库接口,包括自定义查找器方法,Spring将自动提供实现。