Java 通过JPA将记录插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2702661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:01:02  来源:igfitidea点击:

Inserting the record into Database through JPA

javajpa

提问by user324680

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.,

在我的代码中,我使用 JSF - 前端、EJB-中间层和 JPA 连接到 DB。使用 Webservices.Using MySQL 作为数据库调用 EJB。我已经创建了需要在其中插入记录的 Voter 表。我将值从 JSF 传递到 EJB,它正在工作。我创建了 JPA 控制器类(它根据数据库类自动生成持久性代码)例如:获取实体管理器等,

    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)?

任何人都可以帮助我通过 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.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)

回答by Pascal Thivent

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...

我认为您错过了 JPA 的重点。使用 JPA,您不应该编写查询来插入、更新或删除持久对象,JPA 会为您生成它们。因此,您需要做的是创建域对象并对其进行注释以使其“持久”(此类带注释的对象称为实体)并告诉 JPA 引擎如何将它们“映射”到您的数据库。让我试着向你展示正确的道路......

First, create a Voterdomain object and add JPA annotations (an entity class must be annotated with the Entityannotation, must have a no-arg constructor, must implement Serializable, must have a primary key identified by the Idannotation):

首先,创建一个Voter域对象并添加 JPA 注解(实体类必须使用注解进行Entity注解,必须具有无参数构造函数,必须实现Serializable,必须具有由Id注解标识的主键):

@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 Tableor Columnannotations if you need to map your entity to an existing model.

我在这里使用 JPA 的默认值(默认表名、列名等)。但是,如果您需要将实体映射到现有模型,则可以使用TableColumn注释进行自定义。

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 APIfrom the Java EE 5 Tutorial.

这只是一个简短的介绍,一个答案无法涵盖 JPA。为了更进一步,我建议查看Java EE 5 教程中的 Java Persistence API 简介

Update:In a managed component, for example an EJB, the EntityManageris 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 EntityManagerisn'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 EntityManagerannotated? What does your persistence.xmllooks like? Please update your question with the relevant details.

更新:在托管组件中,例如 EJB,EntityManager通常注入 并且事务由容器管理(即您没有显式调用begin/commit)。在您的情况下,我敢打赌EntityManager未成功注入并对其调用任何方法都会导致 NPE。但这只是猜测,您需要提供更多详细信息。你的 EJB 的第 39 行是什么?EntityManager注释是怎么写的?你persistence.xml看起来像什么?请使用相关详细信息更新您的问题。

回答by Williams

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.

我想它不是从构造函数中插入的参数中检索 的值,这会导致 NullPointerExpception。最好使用voter.setPassword(password); 例如将值传入 Voter 实体。还要检查值是否为空。

回答by Williams

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

此外,您不需要再次编写开始和提交事务。像这样:

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

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

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

如果您正在使用容器管理的实体管理器,因为它是由容器自动完成的。

回答by phstorey

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.

我对 JPA、JSF 和所有爵士乐都很陌生,但我希望这会有所帮助。

回答by Meriam

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

如果您使用实体管理器意味着您正在使用 JTA 处理事务,因此实体管理器将由容器处理,您将无法使用

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

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

em.getTransaction()它是一个实体事务,将由 JTA 处理。

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

您需要直接使用persist(),因为您有实体管理器,并且您的数据将被添加。

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.

如果您想使用查询,它总是可以在 aa en.createQuery 中使用...但我不知道它是否可以用作命名查询。