具有继承的通用DAO设计模式。这是一个很好的设计吗?

时间:2014-08-21 06:40:25

标签: spring hibernate generics design-patterns dao

我只想评论一下我从几十个关于通用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实现继承的想法。

  1. 这是一个好习惯吗?反映POJO的层次结构并在DAO中进行?
  2. 我在这里用我的设计做错了吗?因为我有一个完整的程序 从数据库中保存和检索我的对象没有任何问题
  3. 我对任何建议或更正持开放态度。先感谢您!!!

1 个答案:

答案 0 :(得分:1)

不是对设计的评论,但是......你考虑使用Spring Spring Data Jpa,它允许你:

  

编写存储库接口,包括自定义查找器方法,Spring将自动提供实现。