The current application I'm working on is a big one. The database consists of 300+ tables and it's growing. At the moment it's a desktop application but we're moving it to the web.
Technologies we're using for this are Spring (MVC) + Hibernate for backend and ZK framework on the front. Having 300+ tables in database I ended up creating that much POJO's as well. Using Spring's DAO pattern this requires project to have 300+ DAO objects and 300+ Service classes as well.
This is how I'm doing it at the moment:
POJO:
@Entity
@Table(name="test")
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Integer version;
private String m_name;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="jpa_id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Version
@Column(name="jpa_version", insertable=false, updatable=false)
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Column(name="name", length=30)
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
}
Interface for DAO objects:
public interface IDao<T> {
public List<T> getAll();
}
To avoid copy/paste I have created a generic DAO class that will be extended by all DAO objects:
@Repository
public class GenericDAO<T extends Serializable> implements IDao<T> {
@Autowired
protected SessionFactory sessionFactory;
protected Class<T> entity;
@SuppressWarnings("unchecked")
public List<T> getAll() {
List<T> result = (List<T>) getSessionFactory().getCurrentSession().createQuery("from " + entity.getName()).list();
return result;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void setEntity(Class<T> entity) {
this.entity = entity;
}
}
DAO object:
@Repository
public class TestDAO extends GenericDAO<Test> {
public TestDAO() {
setEntity(Test.class);
}
}
Service interface:
public interface IService<T> {
public List<T> getAll();
}
Service implementation:
@Service
public class TestService implements IService<Test> {
@Autowired
private IDao<Test> testDAO;
@Transactional(readOnly=true)
public List<Test> getAll() {
return testDAO.getAll();
}
public void setTestDAO(IDao<Test> testDAO) {
this.testDAO = testDAO;
}
}
I have 2 questions:
How to write a generic service like the GenericDAO class above to avoid c/p?
If you look at the DAO implementaion the only thing there is a constructor. Is there a way to have "one" DAO class that handles all POJO's and one Service class that handles all / one DAO object?