java 实体表未使用 JPA 2.1 创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25489359/
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-11-02 08:06:16  来源:igfitidea点击:

Entity Table is not creating using JPA 2.1

javajpanetbeansejb-3.0jpa-2.1

提问by Lawrence Wong

I am using JPA 2.1 in Netbeans to create my entity. If my database has no table then it should create table from entities.

我在 Netbeans 中使用 JPA 2.1 来创建我的实体。如果我的数据库没有表,那么它应该从实体创建表。

When I deploy and run my enterprise application, the userEntity table does not appear in my mySQL database.

当我部署和运行我的企业应用程序时,userEntity 表没有出现在我的 mySQL 数据库中。

Any help here? :)

这里有什么帮助吗?:)

Below are my codes.

下面是我的代码。

persistence.xml

持久化文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="CommonInfrastructure-ejbPU" transaction-type="JTA">
    <jta-data-source>jdbc/commonInfraDatasource</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

userEntity.java

用户实体.java

package entity;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class userEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long systemUserId;
    private String userName;
    private String password;
    private String email;
    private int activateStatus;
    private String accessGroup;
    private int lockOutStatus;



    @Override
    public int hashCode() {
        int hash = 0;
        hash += (getSystemUserId() != null ? getSystemUserId().hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the systemUserId fields are not set
        if (!(object instanceof userEntity)) {
            return false;
        }
        userEntity other = (userEntity) object;
        if ((this.getSystemUserId() == null && other.getSystemUserId() != null) || (this.getSystemUserId() != null && !this.systemUserId.equals(other.systemUserId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.userEntity[id=" + getSystemUserId() + "]";
    }

    /**
     * @return the systemUserId
     */
    public Long getSystemUserId() {
        return systemUserId;
    }

    /**
     * @param systemUserId the systemUserId to set
     */
    public void setSystemUserId(Long systemUserId) {
        this.systemUserId = systemUserId;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the activateStatus
     */
    public int getActivateStatus() {
        return activateStatus;
    }

    /**
     * @param activateStatus the activateStatus to set
     */
    public void setActivateStatus(int activateStatus) {
        this.activateStatus = activateStatus;
    }

    /**
     * @return the accessGroup
     */
    public String getAccessGroup() {
        return accessGroup;
    }

    /**
     * @param accessGroup the accessGroup to set
     */
    public void setAccessGroup(String accessGroup) {
        this.accessGroup = accessGroup;
    }

    /**
     * @return the lockOutStatus
     */
    public int getLockOutStatus() {
        return lockOutStatus;
    }

    /**
     * @param lockOutStatus the lockOutStatus to set
     */
    public void setLockOutStatus(int lockOutStatus) {
        this.lockOutStatus = lockOutStatus;
    }
}

sun-resources.xml

太阳资源.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
  <jdbc-resource enabled="true" jndi-name="jdbc/commonInfraDatasource" object-type="user" pool-name="CommonInfraConnectionPool">
    <description/>
  </jdbc-resource>
  <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="CommonInfraConnectionPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
    <property name="URL" value="jdbc:XXXXXXXXXX"/>
    <property name="User" value="XXXXXXXXX"/>
    <property name="Password" value="XXXXXXXXX"/>
  </jdbc-connection-pool>
</resources>

Additional Information I start up my Glassfish Server and right click and deploy my enterprise application. This should create the userEntity table in my database right? However,it did not. enter image description here

附加信息 我启动我的 Glassfish 服务器并右键单击并部署我的企业应用程序。这应该在我的数据库中创建 userEntity 表吗?然而,它没有。 在此处输入图片说明

回答by lukasj

to force EclipseLink to create tables during deployment time, add:

要强制 EclipseLink 在部署期间创建表,请添加:

<property name="eclipselink.deploy-on-startup" value="true" />

to your persistence.xml. By default, tables are being created when needed, usually on first access to EMF from the application. This behavior is defined in section 9.4 of the JPA 2.1 spec.

到您的persistence.xml。默认情况下,在需要时创建表,通常是在第一次从应用程序访问 EMF 时。此行为在 JPA 2.1 规范的第 9.4 节中定义。

回答by Lawrence Wong

Anyway, I managed to resolve this problem.

无论如何,我设法解决了这个问题。

You need to do something using JPA before the table can be created.

在创建表之前,您需要使用 JPA 做一些事情。

For example...

例如...

package sessionBean;

import javax.ejb.Stateless;
import entity.userEntity;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

    @Stateless
    public class userSessionBean implements userSessionBeanLocal {

        @PersistenceContext
        private EntityManager entityManager;

        @Override
        public userEntity getUser(String userName) {
            Query query = entityManager.createQuery("SELECT u FROM userEntity u WHERE u.userName = :inUserName");
            query.setParameter("inUserName", userName);
            userEntity systemUser = null;
            try {
                systemUser = (userEntity) query.getSingleResult();
            } catch (NoResultException ex) {
                ex.printStackTrace();
            }
            return systemUser;
        }


    }

回答by The PowerHouse

For me adding a single line in persistence unit worked.

对我来说,在持久性单元中添加一行是有效的。

<property name="hibernate.hbm2ddl.auto" value="create" />

回答by Zorog

Just take note that if you use <property name="hibernate.hbm2ddl.auto" value="create" />

请注意,如果您使用 <property name="hibernate.hbm2ddl.auto" value="create" />

it will clear all the existing data in your database.

它将清除数据库中的所有现有数据。

回答by Paul Vargas

Add the next property in your persistence.xmlfile.

在您的persistence.xml文件中添加下一个属性。

<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>

回答by Nabi

Just in case someone is interested: It seems that since JPA 2.1 / Glassfish 4.1 you need to use your PU somewhere before the tables are created. These two lines should be enough, i.e. in an EJB:

以防万一有人感兴趣:似乎从 JPA 2.1 / Glassfish 4.1 开始,您需要在创建表之前在某处使用 PU。这两行应该足够了,即在 EJB 中:

@PersistenceContext
private EntityManager em;

or

或者

@PersistenceContext(unitName = "CommonInfrastructure-ejbPU")
private EntityManager em;

See also my answer here: How to use JPA with Java EE 7, Glassfish 4.1 and Maven on JavaDB

另请参阅我的回答:How to use JPA with Java EE 7, Glassfish 4.1 and Maven on JavaDB