3

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.

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

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

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

Lawrence Wong
  • 1,129
  • 4
  • 24
  • 40
  • Missing information: this is apparently running on Glassfish and thus the persistence provider is EclipseLink. JPA 2.1 is only an API, it doesn't "do" anything itself; EclipseLink is the implementation which is failing you here. How are you testing this? Are you just starting up the server or are you actually trying to do something using JPA and you are getting a "table not found" error? – Gimby Aug 25 '14 at 15:36
  • Hi Gimby, Refer to my updated post above. Missing 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. – Lawrence Wong Aug 25 '14 at 15:43
  • Not necessarily. It depends on when Glassfish activates the initialization of the JPA subsystem. It might be that to save startup time, that is only done when you first use JPA. Hence I would try to actually do something with JPA (and getting an error) before claiming that "it is not working". But I'm a JBoss guy, so I can only guess based on what I've read about Glassfish (and wondering how it could startup so quickly). – Gimby Aug 25 '14 at 15:47
  • Hi Gimby. Thanks for your suggestion. What do you mean by do something with the JPA? I don't really quite get that part. You mean try retrieving something from the database? – Lawrence Wong Aug 25 '14 at 15:49
  • Hi Gimby! Thanks for your suggestion on do something with JPA. I did that and it worked. Thanks bro! :) – Lawrence Wong Aug 25 '14 at 16:05

6 Answers6

5

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

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

lukasj
  • 126
  • 1
  • 1
4

Anyway, I managed to resolve this problem.

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

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;
        }


    }
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
Lawrence Wong
  • 1,129
  • 4
  • 24
  • 40
  • 1
    why we should do something to create or update the schema of the database? it's not clear, what is the instruction that creates the database, please? – Thamer Mar 03 '19 at 15:56
1

For me adding a single line in persistence unit worked.

<property name="hibernate.hbm2ddl.auto" value="create" />
The PowerHouse
  • 560
  • 14
  • 29
0

Add the next property in your persistence.xml file.

<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0

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:

@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

Community
  • 1
  • 1
Nabi
  • 2,536
  • 1
  • 16
  • 18
0

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

it will clear all the existing data in your database.

Zorog
  • 33
  • 5