Java EE DAO Pattern

Java EE really makes our life easy when dealing with Database Management. Here is a basic DAO design pattern that I use in most of my projects:

public abstract class AbstractDao, ID extends Serializable> {

protected abstract EntityManager getEntityManager();

private Class entity;

public AbstractDao(Class entity) {
this.entity = entity;
}

public T find(ID id) {
return getEntityManager().find(entity, id);
}

public List findAll() {
CriteriaQuery cq = getEntityManager().getCriteriaBuilder()
.createQuery(entity);
cq.select(cq.from(entity));

return getEntityManager().createQuery(cq).getResultList();
}

public List findByPage(int pageNum, int pageSize) {
CriteriaQuery cq = getEntityManager().getCriteriaBuilder()
.createQuery(entity);
cq.select(cq.from(entity));

int firstResult = pageNum * pageSize;
return getEntityManager().createQuery(cq).setFirstResult(firstResult)
.setMaxResults(pageSize).getResultList();
}

public long count() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Long.class);
Root personRoot = cq.from(entity);

cq.select(cb.count(personRoot));

List list = getEntityManager().createQuery(cq).setMaxResults(1)
.getResultList();

long personsNumber = 0l;
if (!list.isEmpty()) {
personsNumber = list.get(0);
}
return personsNumber;
}

public T save(T entity) {
try {
if (entity.getId() == null) {
getEntityManager().persist(entity);
} else {
entity = getEntityManager().merge(entity);
}
} catch (Exception e) {
getLogger().error(e.getMessage());
}
return entity;
}

public T saveAndFlush(T entity) {
try {
entity = save(entity);
flush();
} catch (Exception e) {
getLogger().error(e.getMessage());
}
return entity;
}

public void flush() {
getEntityManager().flush();
}

public List saveAllAndFlush(Collection collection) {
List list = null;
try {
list = collection.parallelStream()
.map(this::save)
.collect(Collectors.toList());
flush();
} catch (Exception e) {
getLogger().error(e.getMessage());
}
return list;
}

public boolean exists(ID id) {
return find(id) != null;
}

protected abstract Logger getLogger();
}



Chris Georgoulis

Chris Georgoulis

Summary:
– Primary programming language: Java SE (SWING, JDBC), Java EE, (JSF – PrimeFaces, JPA – EclipseLink/Hibernate, EJB, CDI ),
– Secondary languages: C/C++, Web Technologies(HTML, XHTML, XML, CSS, JavaScript, jQuery, AngularJS).
– Frameworks: Android SDK, Global Sensors Network (GSN), Open Computer Vision (OpenCV).
– IDE’s: Eclipse, Visual Studio
– Other Apps: MS Office, Photoshop, Dreamweaver
– Database Design – SQL(MySQL), NoSQL(MongoDB)
– Modeling Tools: UML

More Posts