Entity Table is not creating using JPA 2.1

后端 未结 6 899
小蘑菇
小蘑菇 2021-01-21 00:51

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 applicati

相关标签:
6条回答
  • 2021-01-21 01:20

    Add the next property in your persistence.xml file.

    <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
    
    0 讨论(0)
  • 2021-01-21 01:23

    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

    0 讨论(0)
  • 2021-01-21 01:27

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

    it will clear all the existing data in your database.

    0 讨论(0)
  • 2021-01-21 01:32

    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.

    0 讨论(0)
  • 2021-01-21 01:39

    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;
            }
    
    
        }
    
    0 讨论(0)
  • 2021-01-21 01:42

    For me adding a single line in persistence unit worked.

    <property name="hibernate.hbm2ddl.auto" value="create" />
    
    0 讨论(0)
提交回复
热议问题