David R. Heffelfinger

  Ensode Technology, LLC

 
Bookmark and Share

Automated DAO Generation from JPA Entities with NetBeans


One very nice NetBeans feature is the ability to generate Java Persistence API (JPA) entitites from an existing database schema. NetBeans can also generate complete JSF CRUD applications from JPA entities in a project. Both of these features are covered in detail in my Java EE 5 Development With NetBeans book.

As of NetBeans 6.5, scheduled to be released next month, will also add the ability to automatically generate DAO's (NetBeans calls them controllers, but they are, in fact, Data Access Objects) from existing JPA Entities.

NetBeans JPA Controller

This will certainly save us developers a lot of work, here is a sample DAO from generated from the Customer JPA entity discussed in the book:


package com.ensode.customerdb.jpacontrollers;

import com.ensode.customerdb.jpa.Customer;
import com.ensode.customerdb.jpacontrollers.exceptions.NonexistentEntityException;
import com.ensode.customerdb.jpacontrollers.exceptions.PreexistingEntityException;
import com.ensode.customerdb.jpacontrollers.exceptions.RollbackFailureException;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import com.ensode.customerdb.jpa.CustomerOrder;
import java.util.ArrayList;
import java.util.Collection;
import com.ensode.customerdb.jpa.Address;
import com.ensode.customerdb.jpa.Telephone;
import javax.transaction.UserTransaction;

/**
*
* @author heffel
*/
public class CustomerJpaController {
@Resource
private UserTransaction utx = null;
@PersistenceUnit(unitName = "WebApplication1PU")
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
return emf.createEntityManager();
}

public void create(Customer customer) throws PreexistingEntityException, RollbackFailureException, Exception {
if (customer.getCustomerOrderCollection() == null) {
customer.setCustomerOrderCollection(new ArrayList());
}
if (customer.getAddressCollection() == null) {
customer.setAddressCollection(new ArrayList

());
}
if (customer.getTelephoneCollection() == null) {
customer.setTelephoneCollection(new ArrayList());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Collection attachedCustomerOrderCollection = new ArrayList();
for (CustomerOrder customerOrderCollectionCustomerOrderToAttach : customer.getCustomerOrderCollection()) {
customerOrderCollectionCustomerOrderToAttach = em.getReference(customerOrderCollectionCustomerOrderToAttach.getClass(), customerOrderCollectionCustomerOrderToAttach.getCustomerOrderId());
attachedCustomerOrderCollection.add(customerOrderCollectionCustomerOrderToAttach);
}
customer.setCustomerOrderCollection(attachedCustomerOrderCollection);
Collection
attachedAddressCollection = new ArrayList
();
for (Address addressCollectionAddressToAttach : customer.getAddressCollection()) {
addressCollectionAddressToAttach = em.getReference(addressCollectionAddressToAttach.getClass(), addressCollectionAddressToAttach.getAddressId());
attachedAddressCollection.add(addressCollectionAddressToAttach);
}
customer.setAddressCollection(attachedAddressCollection);
Collection attachedTelephoneCollection = new ArrayList();
for (Telephone telephoneCollectionTelephoneToAttach : customer.getTelephoneCollection()) {
telephoneCollectionTelephoneToAttach = em.getReference(telephoneCollectionTelephoneToAttach.getClass(), telephoneCollectionTelephoneToAttach.getTelephoneId());
attachedTelephoneCollection.add(telephoneCollectionTelephoneToAttach);
}
customer.setTelephoneCollection(attachedTelephoneCollection);
em.persist(customer);
for (CustomerOrder customerOrderCollectionCustomerOrder : customer.getCustomerOrderCollection()) {
Customer oldCustomerIdOfCustomerOrderCollectionCustomerOrder = customerOrderCollectionCustomerOrder.getCustomerId();
customerOrderCollectionCustomerOrder.setCustomerId(customer);
customerOrderCollectionCustomerOrder = em.merge(customerOrderCollectionCustomerOrder);
if (oldCustomerIdOfCustomerOrderCollectionCustomerOrder != null) {
oldCustomerIdOfCustomerOrderCollectionCustomerOrder.getCustomerOrderCollection().remove(customerOrderCollectionCustomerOrder);
oldCustomerIdOfCustomerOrderCollectionCustomerOrder = em.merge(oldCustomerIdOfCustomerOrderCollectionCustomerOrder);
}
}
for (Address addressCollectionAddress : customer.getAddressCollection()) {
Customer oldCustomerIdOfAddressCollectionAddress = addressCollectionAddress.getCustomerId();
addressCollectionAddress.setCustomerId(customer);
addressCollectionAddress = em.merge(addressCollectionAddress);
if (oldCustomerIdOfAddressCollectionAddress != null) {
oldCustomerIdOfAddressCollectionAddress.getAddressCollection().remove(addressCollectionAddress);
oldCustomerIdOfAddressCollectionAddress = em.merge(oldCustomerIdOfAddressCollectionAddress);
}
}
for (Telephone telephoneCollectionTelephone : customer.getTelephoneCollection()) {
Customer oldCustomerIdOfTelephoneCollectionTelephone = telephoneCollectionTelephone.getCustomerId();
telephoneCollectionTelephone.setCustomerId(customer);
telephoneCollectionTelephone = em.merge(telephoneCollectionTelephone);
if (oldCustomerIdOfTelephoneCollectionTelephone != null) {
oldCustomerIdOfTelephoneCollectionTelephone.getTelephoneCollection().remove(telephoneCollectionTelephone);
oldCustomerIdOfTelephoneCollectionTelephone = em.merge(oldCustomerIdOfTelephoneCollectionTelephone);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findCustomer(customer.getCustomerId()) != null) {
throw new PreexistingEntityException("Customer " + customer + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}

public void edit(Customer customer) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Customer persistentCustomer = em.find(Customer.class, customer.getCustomerId());
Collection customerOrderCollectionOld = persistentCustomer.getCustomerOrderCollection();
Collection customerOrderCollectionNew = customer.getCustomerOrderCollection();
Collection

addressCollectionOld = persistentCustomer.getAddressCollection();
Collection
addressCollectionNew = customer.getAddressCollection();
Collection telephoneCollectionOld = persistentCustomer.getTelephoneCollection();
Collection telephoneCollectionNew = customer.getTelephoneCollection();
Collection attachedCustomerOrderCollectionNew = new ArrayList();
for (CustomerOrder customerOrderCollectionNewCustomerOrderToAttach : customerOrderCollectionNew) {
customerOrderCollectionNewCustomerOrderToAttach = em.getReference(customerOrderCollectionNewCustomerOrderToAttach.getClass(), customerOrderCollectionNewCustomerOrderToAttach.getCustomerOrderId());
attachedCustomerOrderCollectionNew.add(customerOrderCollectionNewCustomerOrderToAttach);
}
customerOrderCollectionNew = attachedCustomerOrderCollectionNew;
customer.setCustomerOrderCollection(customerOrderCollectionNew);
Collection
attachedAddressCollectionNew = new ArrayList
();
for (Address addressCollectionNewAddressToAttach : addressCollectionNew) {
addressCollectionNewAddressToAttach = em.getReference(addressCollectionNewAddressToAttach.getClass(), addressCollectionNewAddressToAttach.getAddressId());
attachedAddressCollectionNew.add(addressCollectionNewAddressToAttach);
}
addressCollectionNew = attachedAddressCollectionNew;
customer.setAddressCollection(addressCollectionNew);
Collection attachedTelephoneCollectionNew = new ArrayList();
for (Telephone telephoneCollectionNewTelephoneToAttach : telephoneCollectionNew) {
telephoneCollectionNewTelephoneToAttach = em.getReference(telephoneCollectionNewTelephoneToAttach.getClass(), telephoneCollectionNewTelephoneToAttach.getTelephoneId());
attachedTelephoneCollectionNew.add(telephoneCollectionNewTelephoneToAttach);
}
telephoneCollectionNew = attachedTelephoneCollectionNew;
customer.setTelephoneCollection(telephoneCollectionNew);
customer = em.merge(customer);
for (CustomerOrder customerOrderCollectionOldCustomerOrder : customerOrderCollectionOld) {
if (!customerOrderCollectionNew.contains(customerOrderCollectionOldCustomerOrder)) {
customerOrderCollectionOldCustomerOrder.setCustomerId(null);
customerOrderCollectionOldCustomerOrder = em.merge(customerOrderCollectionOldCustomerOrder);
}
}
for (CustomerOrder customerOrderCollectionNewCustomerOrder : customerOrderCollectionNew) {
if (!customerOrderCollectionOld.contains(customerOrderCollectionNewCustomerOrder)) {
Customer oldCustomerIdOfCustomerOrderCollectionNewCustomerOrder = customerOrderCollectionNewCustomerOrder.getCustomerId();
customerOrderCollectionNewCustomerOrder.setCustomerId(customer);
customerOrderCollectionNewCustomerOrder = em.merge(customerOrderCollectionNewCustomerOrder);
if (oldCustomerIdOfCustomerOrderCollectionNewCustomerOrder != null && !oldCustomerIdOfCustomerOrderCollectionNewCustomerOrder.equals(customer)) {
oldCustomerIdOfCustomerOrderCollectionNewCustomerOrder.getCustomerOrderCollection().remove(customerOrderCollectionNewCustomerOrder);
oldCustomerIdOfCustomerOrderCollectionNewCustomerOrder = em.merge(oldCustomerIdOfCustomerOrderCollectionNewCustomerOrder);
}
}
}
for (Address addressCollectionOldAddress : addressCollectionOld) {
if (!addressCollectionNew.contains(addressCollectionOldAddress)) {
addressCollectionOldAddress.setCustomerId(null);
addressCollectionOldAddress = em.merge(addressCollectionOldAddress);
}
}
for (Address addressCollectionNewAddress : addressCollectionNew) {
if (!addressCollectionOld.contains(addressCollectionNewAddress)) {
Customer oldCustomerIdOfAddressCollectionNewAddress = addressCollectionNewAddress.getCustomerId();
addressCollectionNewAddress.setCustomerId(customer);
addressCollectionNewAddress = em.merge(addressCollectionNewAddress);
if (oldCustomerIdOfAddressCollectionNewAddress != null && !oldCustomerIdOfAddressCollectionNewAddress.equals(customer)) {
oldCustomerIdOfAddressCollectionNewAddress.getAddressCollection().remove(addressCollectionNewAddress);
oldCustomerIdOfAddressCollectionNewAddress = em.merge(oldCustomerIdOfAddressCollectionNewAddress);
}
}
}
for (Telephone telephoneCollectionOldTelephone : telephoneCollectionOld) {
if (!telephoneCollectionNew.contains(telephoneCollectionOldTelephone)) {
telephoneCollectionOldTelephone.setCustomerId(null);
telephoneCollectionOldTelephone = em.merge(telephoneCollectionOldTelephone);
}
}
for (Telephone telephoneCollectionNewTelephone : telephoneCollectionNew) {
if (!telephoneCollectionOld.contains(telephoneCollectionNewTelephone)) {
Customer oldCustomerIdOfTelephoneCollectionNewTelephone = telephoneCollectionNewTelephone.getCustomerId();
telephoneCollectionNewTelephone.setCustomerId(customer);
telephoneCollectionNewTelephone = em.merge(telephoneCollectionNewTelephone);
if (oldCustomerIdOfTelephoneCollectionNewTelephone != null && !oldCustomerIdOfTelephoneCollectionNewTelephone.equals(customer)) {
oldCustomerIdOfTelephoneCollectionNewTelephone.getTelephoneCollection().remove(telephoneCollectionNewTelephone);
oldCustomerIdOfTelephoneCollectionNewTelephone = em.merge(oldCustomerIdOfTelephoneCollectionNewTelephone);
}
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = customer.getCustomerId();
if (findCustomer(id) == null) {
throw new NonexistentEntityException("The customer with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}

public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Customer customer;
try {
customer = em.getReference(Customer.class, id);
customer.getCustomerId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The customer with id " + id + " no longer exists.", enfe);
}
Collection customerOrderCollection = customer.getCustomerOrderCollection();
for (CustomerOrder customerOrderCollectionCustomerOrder : customerOrderCollection) {
customerOrderCollectionCustomerOrder.setCustomerId(null);
customerOrderCollectionCustomerOrder = em.merge(customerOrderCollectionCustomerOrder);
}
Collection

addressCollection = customer.getAddressCollection();
for (Address addressCollectionAddress : addressCollection) {
addressCollectionAddress.setCustomerId(null);
addressCollectionAddress = em.merge(addressCollectionAddress);
}
Collection telephoneCollection = customer.getTelephoneCollection();
for (Telephone telephoneCollectionTelephone : telephoneCollection) {
telephoneCollectionTelephone.setCustomerId(null);
telephoneCollectionTelephone = em.merge(telephoneCollectionTelephone);
}
em.remove(customer);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}

public List findCustomerEntities() {
return findCustomerEntities(true, -1, -1);
}

public List findCustomerEntities(int maxResults, int firstResult) {
return findCustomerEntities(false, maxResults, firstResult);
}

private List findCustomerEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Customer as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}

public Customer findCustomer(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Customer.class, id);
} finally {
em.close();
}
}

public int getCustomerCount() {
EntityManager em = getEntityManager();
try {
return ((Long) em.createQuery("select count(o) from Customer as o").getSingleResult()).intValue();
} finally {
em.close();
}
}

}

Isn't it great to get all this code generated? No need to develop and debug it ourselves, letting us focus on implementing business logic.

 
 
 
 
Comments:

There are some for loops which I dont understand. For example in the create method, the first one starts with: for (CustomerOrder customerOrderCollectionCustomerOrderToAttach : customer.getCustomerOrderCollection()) { ... ... } Later on, after persist, we have: for (CustomerOrder customerOrderCollectionCustomerOrder : customer.getCustomerOrderCollection()) { ... ... } What is the purpose of those loops? Thanks in advance, Alberto

Posted by Alberto on January 18, 2009 at 03:51 PM EST #

Alberto,

The Customer JPA entity has a one to many relationship with the CustomerOrder, Address and Telephone JPA entities.

The purpose of the loops is to persist all CustomerOrder, Address and Telephone entities that are related to the Customer entity we are persisting.

David

Posted by David R. Heffelfinger on January 18, 2009 at 05:14 PM EST #

Null pointer exception from
createEntityManager();

Posted by 82.193.22.66 on May 14, 2009 at 08:52 AM EDT #

Post a Comment:
Comments are closed for this entry.
 

« April 2024
SunMonTueWedThuFriSat
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
       
Today

 
© David R. Heffelfinger