开发者

Inserting the record into Database through JPA

In my code I am using JSF - Front end , EJB-Middile Tier and JPA connect to DB.Calling the EJB using the Webservices.Using MySQL as DAtabase. I have created the Voter table in which I need to insert the record. I ma passing the values from the JSF to EJB, it is working.I have created JPA controller class (which automatcally generates the persistence code based on the data base classes) Ex: getting the entity manager etc.,

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

I have created the named query also:

@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 still not able to insert the record?

Can anyone help me in inserting the record into the Data base through JPA.(Persistence object)?

Update:

If we are using the container managed entity manager, should we need to write begin and commit transactions again... like this:

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

I have written:

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

But it is resulting to Null pointer exception.

SEVERE: 开发者_JAVA百科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)


I think that you missed the point of JPA. With JPA, you're not supposed to write queries to insert, update or delete persistent objects, JPA will generate them for you. So, what you need to do is to create domain objects and to annotate them to make them "persistable" (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 path...

First, create a Voter domain object and add JPA annotations (an entity class must be annotated with the Entity annotation, must have a no-arg constructor, must implement Serializable, must have a primary key identified by the 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'm using JPA's defaults here (default table name, column name, etc). But this can be customized using the Table or Column annotations if you need to map your entity to an existing model.

Then, create a new instance and set the various attributes:

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

And persist it:

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

This is just a short introduction, JPA can't be covered in one answer. To go further, I suggest to check the Introduction to the Java Persistence API from the Java EE 5 Tutorial.

Update: In a managed component, for example an EJB, the EntityManager is typically injected and transactions are managed by the container (i.e. you don't explicitly call begin/commit). In your case, my bet is that the EntityManager isn't successfully injected and calling any method on it results in a NPE. But that's just a guess, you need to provide more details. What is the line 39 of your EJB? How is the EntityManager annotated? What does your persistence.xml looks like? Please update your question with the relevant details.


Also, you dont need to write begin and commit transactions again.Like this :

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

if only you are using container managed Entity Managers because it is automatically done by the container.


I guess it is not retrieving the values of from the parameters inserted in the constructor which leads to a NullPointerExpception. It is better if you use voter.setPassword(password); for example to pass in values into the Voter entity. Also check if the values are empty.


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

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

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

Parameter name would be using your example "password" or "attribute" basically whatever follows the colon.

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


if you re using the entity manager means you re handling transaction with JTA, so the entity manager will be handled by the container, you re not be able to use

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

em.getTransaction() it s an entity transaction which will be handled by JTA .

You ll need to directly use the persist(), as you have the entitymanager, and you re data will be addedd.

If you want to use the query it s always possible in a a en.createQuery ... But I don t know if it can be use as a named query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜