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.