Welcome!

Apache Authors: Pat Romanski, Liz McMillan, Elizabeth White, Christopher Harrold, Janakiram MSV

Related Topics: @CloudExpo, Java IoT, Machine Learning , Apache

@CloudExpo: Blog Feed Post

Translating the NetBeans Generated JPA Controller | @CloudExpo [#Cloud]

The NetBeans New File wizards greatly simplify writing boilerplate code

The NetBeans New File wizards greatly simplify writing boilerplate code. One specific instance is the creation of JPA Controller Classes from an Entity Classes. The class file, or files, written for you will contain all the basic methods of JPA for CRUD operations on the entity or entities that you have. The only small issue is that this class is written for a standalone environment such as what you would find in an environment that does not support Context Dependency Injection. To use this class in a GlassFish environment or other container we have to make some minor changes.

When working with GlassFish the first step is to create the glassfish-resources.xml and then the persistence.xml file. If the database and its tables have not been created yet then this is the time to do this. Now create the Entity Classes from Database, also shown in the New File dialog below.

With all this in place you simply have to create a New File for the project in the category Persistence and the File Type of JPA Controller Classes from Entity Classes.

Image01

The next dialog will ask you which entities you wish to have a controller class written for. It should show you the entities you have created for your project. They will appear in the Available Entity Classes box and you use the buttons to move the ones that you want. In my example there is just one entity and I have added it to the Selected Entities Classes box.

Image02

In the next step you must select the package name for the classes that will be created for you. You can use a package that already exists.

Image03

When you Finish you will see the package you created with a file that has the name of the Entity class followed by JpaController.java. In my example it is FishJpaController.java. You will also find an additional package that ends in exceptions that contains custom Exception classes that provide more informative exception types.

Image04

When you open the file you will see the class that has been written for you.

package com.kenfogel.beans;

import com.kenfogel.beans.exceptions.NonexistentEntityException;
import com.kenfogel.beans.exceptions.RollbackFailureException;
import com.kenfogel.entities.Fish;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;

/**
*
* @author Ken
*/
public class FishJpaController implements Serializable {

public FishJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;

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

public void create(Fish fish) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(fish);
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 void edit(Fish fish) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
fish = em.merge(fish);
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 = fish.getId();
if (findFish(id) == null) {
throw new NonexistentEntityException("The fish 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();
Fish fish;
try {
fish = em.getReference(Fish.class, id);
fish.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The fish with id " + id + " no longer exists.", enfe);
}
em.remove(fish);
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<Fish> findFishEntities() {
return findFishEntities(true, -1, -1);
}

public List<Fish> findFishEntities(int maxResults, int firstResult) {
return findFishEntities(false, maxResults, firstResult);
}

private List<Fish> findFishEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Fish.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}

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

public int getFishCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Fish> rt = cq.from(Fish.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}

}

The changes that you have to make are quite straightforward. First, we need to make this class a managed bean and change the EntityManager and UserTransaction into Injected references.

@Named
@SessionScoped
public class FishJpaControllerUpdate implements Serializable {

@Resource
private UserTransaction utx;

@PersistenceContext
private EntityManager en;

NetBeans will help you in adding the necessary imports. The next step is to delete the constructor. As a managed bean you must have a default constructor. If you dislike not seeing a constructor in your class then you can add an empty one.

/**
* Default constructor
*/
public FishJpaControllerUpdate() {
}

Delete the method getEntityManager(). CDI will take care of creating the EntityManager for you.

The last step is to modify every method in the class that has as a first line:

EntityManager em = null;

We don’t need to call upon getEntityManager nor do we need to close the EntityManager when we are finished.

The create method:

public void create(Fish fish) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(fish);
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();
}
}
}

Becomes:

public void create(Fish fish) throws RollbackFailureException, Exception {
try {
utx.begin();
em.persist(fish);
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;
}
}

The query method findFishEntities:

private List<Fish> findFishEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Fish.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}

Becomes:

private List<Fish> findFishEntities(boolean all, int maxResults, int firstResult) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Fish.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
}

Clean up the rest of the methods and your controller will look like, with my added comments, the following:

package com.kenfogel.beans;

import com.kenfogel.beans.exceptions.NonexistentEntityException;
import com.kenfogel.beans.exceptions.RollbackFailureException;
import com.kenfogel.entities.Fish;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;

/**
*
* @author kfogel
*/
@Named
@SessionScoped
public class FishJpaControllerUpdate implements Serializable {

@Resource
private UserTransaction utx;

@PersistenceContext
private EntityManager em;

/**
* Default constructor
*/
public FishJpaControllerUpdate() {
}

/**
* Take a new or detached entity and add it as a new record in the table
*
* @param fish
* @throws RollbackFailureException
* @throws Exception
*/
public void create(Fish fish) throws RollbackFailureException, Exception {
try {
utx.begin();
em.persist(fish);
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;
}
}

/**
* Take a detached entity and update the matching record in the table
*
* @param fish
* @throws NonexistentEntityException
* @throws RollbackFailureException
* @throws Exception
*/
public void edit(Fish fish) throws NonexistentEntityException, RollbackFailureException, Exception {
try {
utx.begin();
fish = em.merge(fish);
utx.commit();
} catch (NotSupportedException | SystemException | RollbackException |
HeuristicMixedException | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
try {
utx.rollback();
} catch (IllegalStateException | SecurityException | SystemException 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 = fish.getId();
if (findFish(id) == null) {
throw new NonexistentEntityException("The fish with id " + id + " no longer exists.");
}
}
throw ex;
}
}

/**
* Delete the record that matched the primary key. Verify that the record exists before deleting it.
*
* @param id
* @throws NonexistentEntityException
* @throws RollbackFailureException
* @throws Exception
*/
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
try {
utx.begin();
Fish fish;
try {
fish = em.getReference(Fish.class, id);
fish.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The fish with id " + id + " no longer exists.", enfe);
}
em.remove(fish);
utx.commit();
} catch (NotSupportedException | SystemException | NonexistentEntityException | RollbackException | HeuristicMixedException | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
try {
utx.rollback();
} catch (IllegalStateException | SecurityException | SystemException re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
}
}

/**
* Return all the records in the table
*
* @return
*/
public List<Fish> findFishEntities() {
return findFishEntities(true, -1, -1);
}

/**
* Return some of the records from the table. Useful for paginating.
*
* @param maxResults
* @param firstResult
* @return
*/
public List<Fish> findFishEntities(int maxResults, int firstResult) {
return findFishEntities(false, maxResults, firstResult);
}

/**
* Either find all or find a group of fish
*
* @param all True means find all, false means find subset
* @param maxResults Number of records to find
* @param firstResult Record number to start returning records
* @return
*/
private List<Fish> findFishEntities(boolean all, int maxResults, int firstResult) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Fish.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
}

/**
* Find a record by primary key
*
* @param id
* @return
*/
public Fish findFish(Integer id) {
return em.find(Fish.class, id);
}

/**
* Return the number of records in the table
*
* @return
*/
public int getFishCount() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Fish> rt = cq.from(Fish.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
System.out.println("fish count: " + ((Long) q.getSingleResult()).intValue());
return ((Long) q.getSingleResult()).intValue();
}
}

You are now ready to use this controller class in your JPA/CDI project.

Read the original blog entry...

More Stories By Ken Fogel

In 1980 I bought for myself the most wonderful toy of the day, the Apple ][+. Obsession followed quickly and by 1983 I was writing software for small and medium sized businesses in Montreal for both the Apple and the IBM PC under the company name Omnibus Systems. In the evenings I taught continuing education courses that demystified the computer to the first generation of workers who found themselves with their typewriter on the scrap heap and a PC with WordStar taking its place.

In 1990 I was invited to join the faculty at Dawson College in the Computer Science Technology program. When I joined the program the primary language was COBOL and my responsibility was to teach small systems languages such as BASIC and C/C++.

Today I am now the chairperson and program coordinator of the Computer Science Technology program at Dawson. The program's primary language is Java and the focus is on enterprise programming.

I like to write about the every day problems my students and I face in using various languages and platforms to get the job done. And from time to time I stray from the path and write about what I plan to do, what I actually get around to doing, and what I imagine I am doing.

@omniprof

@ThingsExpo Stories
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...