简体   繁体   中英

How to use JPA with Java EE 7, Glassfish 4.1 and Maven on JavaDB

I've got a simple Web Java EE 7 project from Maven Archetype (NetBeans: New Project... -> Maven -> Project from Archetype -> webapp-javaee 7) and I'd like to use JPA in order to map classes to database-tables. So I created a new JavaDB database and created the corresponding Connection Pool and JDBC-Ressource in Glassfish. Now i generated a very simple Entity-Class, having all the necessary annotations. NetBeans gives me a hint, saying that a persistence unit is not declared, so i created a persistence.xml file as follows:

<?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="com.mycompany_mavenproject1_war_1.0-SNAPSHOTPU" transaction-type="JTA">
    <jta-data-source>jdbc/testDb</jta-data-source>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

Maven automatically added following dependencies:

<dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.2</version>
        <scope>provided</scope>
    </dependency>

Then i built the project and deployed it on Glassfish. Even though I don't get any errors it just doesn't work, meaning that no corresponding table is being created in the database.

I'm pretty sure that the connection with the database is ok, because it does work with those Sample Projects which are delivered with NetBeans. So i presume that one needs some extra maven-dependency or some special property in the persistence.xml file. I tried just about anything i could find on the internet but nothing seems to work...

You are doing absolutely nothing wrong. It seems that since JPA 2.1 / Glassfish 4.1 you need to use your PU somewhere before the tables are created. I know it was not like this in Glassfish 3.x and I was also a little confused at first. It should be enough to use this code somewhere in your code, ie in an EJB:

@PersistenceContext
private EntityManager em;

or

@PersistenceContext(unitName = "com.mycompany_mavenproject1_war_1.0-SNAPSHOTPU")
private EntityManager em;

See also this answer: Entity Table is not creating using JPA 2.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM