Skip to content
Advertisement

Tables not generated using Derby and OpenJPA

Tables are not generated in database even when i set attribute javax.persistence.schema-generation.database.action to create and connection string javax.persistence.jdbc.url to jdbc:derby:db;create=true

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
    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 https://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="DataLayer"
        transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>DataSource</non-jta-data-source>
        <properties>
            <property
                name="javax.persistence.schema-generation.database.action"
                value="create" />
            <property name="javax.persistence.jdbc.driver"
                value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:derby:db;create=true" />
        </properties>
    </persistence-unit>
</persistence>

my testing method:

HashMap<String, String> jpaProps = new HashMap<String, String>();
jpaProps.put("javax.persistence.jdbc.url", "jdbc:derby:db;create=true");
jpaProps.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
jpaProps.put("javax.persistence.schema-generation.database.action", "create");
EntityManagerFactory factory = Persistence.createEntityManagerFactory("DataLayer", jpaProps);
EntityManager manager = factory.createEntityManager();
EntityPerson person = new EntityPerson();
person.setAge(25);
person.setName("Michael Pear");
manager.getTransaction().begin();
manager.persist(person); 
manager.getTransaction().commit(); //<- Exception here saying EntityPerson Table does not exist.

As you can see, I also tried to override properties by supplying them to createEntityManagerFactory method.

My EntityPerson class:

@Entity
public class EntityPerson
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @Column(nullable = false)
    private String name;
    
    private int age;
    
    ... getters and setters
}

Also tried excplicitly define Table name and Entity name with annotations:

@Entity(name = "EntityPerson")
@Table(name = "EntityPerson")

How to generate tables in db by annotated classes by startup of a program (during runtime)?

Advertisement

Answer

Java EE can discover entities automatically, but as i am building desktop application aka. using Java SE, i needed to mention entities in persistence-unit in persistence.xml file like so:

<class>entities.EntityPerson</class>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement