Welcome!

Java IoT Authors: Automic Blog, Liz McMillan, Pat Romanski, Kevin Benedict, Elizabeth White

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
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – 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 results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis 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. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote 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. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani 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. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata 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. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...