Insert record into database via JPA

In my code I use JSF - Front end, EJB-Middile Tier and JPA connect to DB.Calling EJB using Webservices.Using MySQL as DAtabase. I created a Voter table in which I need to insert a record. I pass values ​​from JSF to EJB, it works. I created a JPA controller class (which automatically generates a save code based on the database classes) Example: getting the object manager, etc.,

em = getEntityManager(); em.getTransaction().begin(); em.persist(voter); em.getTransaction().commit(); 

I also created a named query:

 @NamedQuery(name = "Voter.insertRecord", query = "INSERT INTO Voter v values v.voterID = :voterID,v.password = :password,v.partSSN = :partSSN, v.address = :address, v.zipCode = :zipCode,v.ssn = :ssn, v.vFirstName = :vFirstName,v.vLastName = :vLastName,v.dob = :dob"), 

But is it still not possible to insert a record?

Can someone help me insert a record into the database via JPA. (Persistence Object)?

Update:

If we use the container-managed entity manager, we need to write transactions again and again ... for example:

 em.getTransaction().begin(); em.getTransaction().commit(); 

I wrote:

 Voter v= new Voter(voterID,password,partSSN,address,zipCode,ssn,vFirstName,vLastName,d1,voterFlag); em.persist(v); 

But this leads to a null pointer exception.

 SEVERE: java.lang.NullPointerException at ejb.Registration.reg(Registration.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052) at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124) at com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:4038) at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5223) 
+4
source share
5 answers

I think you missed the jpa point. With JPA, you do not have to write requests to insert, update or delete persistent objects; JPA will generate them for you. So, you need to create domain objects and annotate them to make them “persistent” (such annotated objects are called entities) and tell the JPA engine how to “map” them to your database. Let me try to show you the right way ...

First create a Voter domain object and add JPA annotations (the entity class must be annotated with Entity annotation, must have no-arg constructor, must be Serializable , must have an identified primary key using Id annotation):

 @Entity public class Voter implements Serializable { private Long id; private String firstName; private String lastName; private String password; // other attributes // No-arg constructor public Voter() {} @Id @GeneratedValue // property access is used public Long getId() { return this.id; } protected void setId(Long id) { this.id = id; } // other getters, setters, equals, hashCode } 

I use JPA defaults here (default table name, column name, etc.). But this can be customized using Table or Column annotations if you need to map an object to an existing model.

Then create a new instance and set various attributes:

 Voter voter = new Voter(); voter.setFirstName(firstName); voter.setLastName(lastName); ... 

And go on:

 em.getTransaction().begin(); em.persist(voter); em.getTransaction().commit(); 

This is a brief introduction; JPA cannot be covered in one answer. To continue, I suggest checking out the Introduction to the Java Persistence API from the Java EE 5 Tutorial.

Update: In a managed component, such as EJB, usually an EntityManager is introduced, and transactions are managed by the container (i.e. you do not explicitly call begin/commit ). In your case, my bet is that the EntityManager not successfully entered and calling any method on it leads to NPE. But this is just an assumption, you need to provide more detailed information. What is line 39 of your EJB? How to annotate EntityManager ? What does your persistence.xml look like? Please update your question with relevant information.

+23
source

I assume that it does not extract values ​​from the parameters inserted into the constructor, which leads to a NullPointerExpception. Better if you use voter.setPassword (password); for example, pass values ​​to a Voter object. Also check if the values ​​are empty.

+1
source

In addition, you do not need to write the beginning and make transactions again. Like this:

em.getTransaction().begin(); em.getTransaction().commit();

if you use container-managed Entity Manager, because it is automatically executed by the container.

+1
source

Pascal is right, you can do it. If you want to use named queries, you can do it like this:

Write a method that takes the value (s) you want to set, and use this.

 Query q = em.createNamedQuery("NamedQueryXYZ").setParameter("parameter name", valueToSet) 

The parameter name will use your example “password” or “attribute” in the main, which follows the colon.

I am new to JPA, JSF and all this jazz, but hope this helps.

+1
source

if you use the object manager, then you are processing the transaction using the JTA, so the entity manager will be processed by the container, you will not be able to use

  em.getTransaction().begin(); em.getTransaction().commit(); 

em.getTransaction() is an entity transaction that will be processed by the JTA.

You will need to use persist() directly, since you have noun, and you will add data.

If you want to use a query, this is always possible in en.createQuery ... But I don’t know if it can be used as a named query.

+1
source

Source: https://habr.com/ru/post/1307847/


All Articles