I'm feeling really stupid having to ask this. But I've been looking at my code for 4 hours and can't figure it out. I have rebuild my database several times and can't get it to work.
One of my tables isn't being created for some reason. I have 4 tables game, developer, gameimage and user. User isn't being created but the other are being created perfectly and working. I'm sure it's a stupid mistake but I just don't see it.
If someone could just tell me why this might be happening that would be great.
I'm using toplink
Here is my code:
persistence xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="GameDatabasePU" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>domainmodel.Game</class>
<class>domainmodel.GameImage</class>
<class>domainmodel.Developer</class>
<class>domainmodel.User</class>
<properties>
<property name="toplink.jdbc.user" value="app"/>
<property name="toplink.jdbc.password" value="app"/>
<property name="toplink.jdbc.url" value="jdbc:derby://localhost:1527/Gamedatabase;create=true"/>
<property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="toplink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
User:
#Entity
public class User {
#Id
private String username;
private String password;
private String firstName;
private String surname;
public User() {
}
public User(String naam, String pas){
setUsername(naam);
setPassword(pas);
}
public User(String naam, String pas, String firstName, String surname){
setUsername(naam);
setPassword(pas);
setFirstName(firstName);
setSurname(surname);
}
public void setUsername(String naam){
this.username=naam;
}
//methods
}
Not realy an answer but more some tips to narrow the problem down.
1) Try removing all other classes from your persistence.xml (comment out annotations on other classes)
Maybe the problem is in another class and the output is misleading.
2) Try setting the debug/output level to another level (DEBUG, FINE, FINEST) and get the JPA provider to expose queries.
For TopLink I think adding this to your prersistence properties section will do the trick:
<property name="toplink.logging.level" value="FINEST" />
3) Which database are you using? MySql, PostgreSQL, HSQL, SQL-server?
Some databases don't (fully) support some things.
4) Shouldn't matter, but anyway;
Annotate your User class with #Table(name = "user") or #Table(name = "usera") this will make certain the table name isn't the problem.
Related
I am trying to resolve this problem since 3 days, I cannot solve it. I read about, that IntelliJ is mixing up something. I found that thread and similar answers in other threads, and tried to to exactly the same, but it did not work: Cannot resolve column 'USERNAME' less
My Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<class>Book</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"></property>
<property name="hibernate.show_sql" value="true"></property>
</properties>
</persistence-unit>
</persistence>
My class Book where I want to set the name. The Table "Book" cannot be resolved.
#Entity
#Table(name = "BOOK")
public class Book implements Serializable{
#Id
private int id;
}
In addition to what the answer you posted, in the persistence tool window
(view -> tool windows -> persistence), you should see persistence.xml, right click and select "assign data source" and assign your configured datasource.
More info here: My Favorited Question
I created the small JPA project to persist a Student record. I use Oracle database. I use the OpenJPA as the JPa provider.
I have created the Table student and relevant sequences correctly.
Student Entity class
#Entity
#Table(name = "Student")
public class Student implements Serializable {
private int id;
private String name;
private static final long serialVersionUID = 1L;
public Student() {
super();
}
#Id
#Column(name = "ID")
#SequenceGenerator(name = "TRAIN_SEQ", sequenceName = "STUDENT_SEQ")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TRAIN_SEQ")
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "NAME")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPAOracleDemo">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>com.jpa.demo.model.Student</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:#TEST:50111:TESTPEGAD1" />
<property name="openjpa.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
<property name="openjpa.ConnectionUserName" value="admin" />
<property name="openjpa.ConnectionPassword" value="admin" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
<property name="openjpa.jdbc.Schema" value="MYSCHEMA" />
</properties>
</persistence-unit>
</persistence>
Client Class
OpenJPAEntityManager em = JPAUtil.getEntityManager();
OpenJPAEntityTransaction tx = em.getTransaction();
tx.begin();
// Create the instance of Employee Entity class
Student student = new Student();
student.setName("A.Ramesh");
// JPA API to store the Student instance on the database.
em.persist(student);
tx.commit();
em.close();
System.out.println("Done...");
Util class
private static OpenJPAEntityManagerFactory emf = OpenJPAPersistence
.createEntityManagerFactory("JPAOracleDemo", "META-INF/persistence.xml");
private static OpenJPAEntityManager entManager;
/**
* No need to create any instance for this Util.
*/
private JPAUtil() {
}
/**
* Get {#link EntityManager}.
*
* #return the {#link EntityManager}
*/
public static OpenJPAEntityManager getEntityManager() {
if (entManager == null || !entManager.isOpen()) {
entManager = emf.createEntityManager();
}
return entManager;
}
The data persist in the student table successfully, but I have the bellow error
Exception in thread "Attachment 60230" java.lang.UnsupportedOperationException: cannot get the capability, performing dispose of the retransforming environment
at com.ibm.tools.attach.javaSE.Attachment.loadAgentLibraryImpl(Native Method)
at com.ibm.tools.attach.javaSE.Attachment.loadAgentLibrary(Attachment.java:253)
at com.ibm.tools.attach.javaSE.Attachment.parseLoadAgent(Attachment.java:235)
at com.ibm.tools.attach.javaSE.Attachment.doCommand(Attachment.java:154)
at com.ibm.tools.attach.javaSE.Attachment.run(Attachment.java:116)
Exception in thread "main" java.lang.UnsupportedOperationException: cannot get the capability, performing dispose of the retransforming environment
at sun.instrument.InstrumentationImpl.isRetransformClassesSupported0(Native Method)
at sun.instrument.InstrumentationImpl.isRetransformClassesSupported(InstrumentationImpl.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.apache.openjpa.enhance.ClassRedefiner.canRedefineClasses(ClassRedefiner.java:123)
at org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:122)
at org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:304)
at org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:228)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:202)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:156)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:213)
at com.ibm.ws.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:45)
at com.ibm.ws.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:30)
at com.jpa.demo.util.JPAUtil.getEntityManager(JPAUtil.java:32)
at com.jpa.demo.client.JPAClient.main(JPAClient.java:13)
1045 JPAOracleDemo INFO [main] openjpa.Enhance - Creating subclass for "[class com.jpa.demo.model.Student]". This means that your application will be less efficient and will consume more memory than it would if you ran the OpenJPA enhancer. Additionally, lazy loading will not be available for one-to-one and many-to-one persistent attributes in types using field access; they will be loaded eagerly instead.
Done...
Java version
JDK 1.6
Anybody please let me know what is the issue here?
Updated:
I used the IBM Rational Software Architect for Websphere Software for this development. this problem is with this IDE. When I create the JPA project by default it adds the IBM jre. I just removed the IBM jre and tried with the SUN jre then it was success. Please let me know why this function does not support with IBM jre?
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
For starters, get rid of that property.
This is my enhancer template, this works properly for OPENJPA:
`
<path id="enhance.cp">
<pathelement location="${basedir}${file.separator}${build.dir}" />
<fileset dir="${basedir}${file.separator}ext_libs/">
<include name="**/*.jar" />
</fileset>
</path>
<property name="cp" refid="enhance.cp" />
<target name="openjpa.libs.check" unless="openjpa.libs">
<fail message="Please set -Dopenjpa.libs in your builder configuration!" />
</target>
<target name="build.dir.check" unless="build.dir">
<fail message="Please set -Dbuild.dir in your builder configuration!" />
</target>
<target name="enhance" depends="openjpa.libs.check, build.dir.check">
<echo message="${cp}" />
<taskdef name="openjpac" classname="org.apache.openjpa.ant.PCEnhancerTask">
<classpath refid="enhance.cp" />
</taskdef>
<openjpac>
<classpath refid="enhance.cp" />
<configpropertiesFile="${basedir}${file.separator}src${file.separator}main${file.separator} resources${file.separator}META-INF${file.separator}persistence.xml" />
</openjpac>
</target>
`
The JPA spec requires some type of monitoring of Entity objects, but the spec does not define how to implement this monitoring. Some JPA providers auto-generate new subclasses or proxy objects that front the user's Entity objects at runtime, while others use byte-code weaving technologies to enhance the actual Entity class objects. OpenJPA supports both mechanisms, but strongly suggests only using the byte-code weaving enhancement. The subclassing support (as provided by OpenJPA) is not recommended (and is disabled by default in OpenJPA 2.0 and beyond).(Source: http://openjpa.apache.org/entity-enhancement.html)
The cause of this issue is I used the subclassing support for the entity enhancement but that is disabled by default in OpenJPA2.0 and beyond.
I found the solution for this issue. We have to enhance the entity class at run time by providing a javaagent when launching the JVM that OpenJPA is going run in.
I put something like the following as a JVM argument
-javaagent:C:/OpenJPA/apache-openjpa-2.0.0/openjpa-2.0.0.jar
And I removed the bellow line from persistence.xml
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
Working persistence.xml
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="DataSourceDemo">
<jta-data-source>oracleDS</jta-data-source>
<class>com.auditlog.model.BatchPrint</class>
<properties>
<property name="openjpa.ConnectionUserName" value="admin" />
<property name="openjpa.ConnectionPassword" value="test" />
<property name="openjpa.jdbc.Schema" value="defaultScheme" />
</properties>
</persistence-unit>
</persistence>
We are using Hibernate at my workplace on some project and I had to modify some queryes recently. I found it really cumbersome to modify a query, run an ant smart or ant refresh and see whether my query works. When I asked one of my colleagues he told me that it is the way we use it.
Do you have any idea how can I speed up this process? I'm looking for a tool which can connect to a database (we are using PGSQL) and run my Hibernate query there and show the results without touching ant.
For example I would be able to try this:
#Query(query = "SELECT DISTINCT l FROM Line l, IN(l.workplaces) w WHERE w.workshop.sid=:wsid", params = "wsid")
JBoss Tools for eclipse has a HQL editor that you can open from the hibernate perspective, you can test hql queries there.
We have a junit-Test for hibernate which uses the derby database as a in-memory databse. This will create the database in derby with all tables and you should be able to execute the query, to see if it is valid.
We have all queries in the orm.xml, so those queries are already checked when creating the EntityManager.
setup
private static EntityManagerFactory emf;
private static EntityManager em;
#BeforeClass
public static void before()
{
emf = Persistence.createEntityManagerFactory("persistenztest");
em = emf.createEntityManager();
}
test
#Test public void test()
{
Query q = em.createQuery(YOUR_QUERY_HERE);
List<?> list = q.getResultList();
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persistenztest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>orm.xml</mapping-file>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="hibernate.connection.url" value="jdbc:derby:memory:sa;create=true;territory=de_DE;collation=TERRITORY_BASED:SECONDARY;"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cglib.use_reflection_optimizer" value="false" />
</properties>
</persistence-unit>
</persistence>
I am quite a newbie to Spring JPA in cooperation with ObjectDB database, but I have encountered a problem that I cannot work out.
I have an application written with the mentioned technologies and it works OK, it persists new entities etc. (thus I think there is no problem with the configuration beans), except for updating even the simplest OneToMany/ManyToOne relations. Those updates are not persisted to the database and I cannot figure out why. Here's the snippet of my code:
Entity Team (1:N):
#Entity
public class Team implements Serializable {
...
List<Player> squad;
...
#OneToMany(mappedBy="team", cascade=CascadeType.PERSIST)
public List<Player> getSquad() {
return squad;
}
...
}
Entity Player (N:1)
#Entity
public class Player implements Serializable {
...
private Team team;
...
#ManyToOne
public Team getTeam() {
return team;
}
...
}
Here is a snippet from controller using both DAO objects and the problem:
public ModelAndView addPlayer(HttpServletRequest request, HttpServletResponse response) throws Exception {
...
Team t = teamDao.getTeamById(1); // retrieves an object with ID=1
Player p = playerDao.getPlayerById(1); // retrieves a player with ID=1
t.getSquad().add(p); // adds a player to the squad -> working fine but does not persist
System.out.println("Size of squad: " + t.getSquad().size()); // the player is there
...
return new ModelAndView("index.jsp", "team", t);
}
When I try to list all players in the team inside the index.jsp page or try to add another player the same way, the squad is always empty - nothing persisted to the database. Neither the team object, nor the player object. What do I do wrong?
Any help would be appreciated. Thanks.
EDIT: here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="NewPU" transaction-type="RESOURCE_LOCAL">
<provider>com.objectdb.jpa.Provider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="C:/file.odb" />
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
P.S. The absolute path "C:/file.odb" is only for demonstration purposes.
and here is Spring configuration:
<mvc:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="NewPU" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
CascadeType.PERSIST cascades the persistens of a new object but you load a player from the database and attach the player to your team. If you want to cascade that you have to add the CascadeType.MERGE
cascade = {CascadeType.PERSIST, CascadeType.MERGE}
You may have a look at CascadeType.ALL.
I'm new to JPA and I'm having problems with the autogeneration of primary key values.
I have the following entity:
package jpatest.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private String someProperty;
public String getSomeProperty() {
return someProperty;
}
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public MyEntity() {
}
public MyEntity(String someProperty) {
this.someProperty = someProperty;
}
#Override
public String toString() {
return "jpatest.entities.MyEntity[id=" + id + "]";
}
}
and the following main method in other class:
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPATestPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
MyEntity e = new MyEntity("some value");
em.persist(e); /* (exception thrown here) */
em.getTransaction().commit();
em.close();
emf.close();
}
This is my persistence unit:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="JPATestPU" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>jpatest.entities.MyEntity</class>
<properties>
<property name="toplink.jdbc.user" value="..."/>
<property name="toplink.jdbc.password" value="..."/>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/jpatest"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
When I execute the program I get the following exception in the line marked with the proper comment:
Exception in thread "main" java.lang.IllegalArgumentException: Object: jpatest.entities.MyEntity[id=null] is not a known entity type.
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3212)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:205)
at jpatest.Main.main(Main.java:...)
What am I missing?
I ran into this same problem using NetBeans IDE 6.9.
Apparently, this is a known issue.
See
http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/metamodel_api#DI_101:_20100218:_Descriptor.javaClass_is_null_on_a_container_EM_for_a_specific_case.
Also see http://netbeans.org/bugzilla/show_bug.cgi?id=181068.
I added the last line below to persistence.xml and it fixed it for me.
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- Add the following to work around exception issue -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
As Charles pointed out in his answer, the problem is not the id generation, but the persistence layer not finding the entity.
As you, I am also new to JPA. I have tried to write a "Hello World" JPA application using org.eclipse.persistence.jpa.PersistenceProvider when I got this error. The mentioned workaround also worked for me. Moreover, through trial-error I also found that to declare your entities, you must always anotate #entity in each entity and:
if you set exclude-unlisted-classes to true, you also have to list the entities within class elements in your persistence.xml
if you set exclude-unlisted-classes to false the persistence layer can find the entities regardles of the class element in your persistence.xml.
TopLink used to require you to explicitly set GenerationType.IDENTITY for MySQL, so change this and drop the database. Then try running your sample again. Further you might also want to explcitly set the database platform:
<property name="toplink.platform.class.name"
value="oracle.toplink.platform.database.MySQL4Platform"/>
Also I vaguely remember that you have to run Toplink using its Java agent in order to make it function properly with a resource local entitymanager.
I did however successfully run your example using EclipseLink (which you should use since Toplink is outdated). Only cavat was that I did not have MySQL server handy, so I ran it using H2. I used the following Maven pom.xml to resolve the dependencies:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.randompage</groupId>
<artifactId>sandbox</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>sandbox</name>
<repositories>
<repository>
<id>EclipseLink Repo</id>
<url>http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.0.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.2.130</version>
</dependency>
</dependencies>
</project>
and this persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPATestPU" transaction-type="RESOURCE_LOCAL">
<provider>
org.eclipse.persistence.jpa.PersistenceProvider
</provider>
<class>org.randompage.MyEntity</class>
<properties>
<property name="javax.persistence.jdbc.user" value="johndoe"/>
<property name="javax.persistence.jdbc.password" value="secret"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/.h2/testdb;FILE_LOCK=NO"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
With these settings your code ran as expected.
I use this syntax rather than type AUTO
#javax.persistence.Id
#javax.persistence.GeneratedValue(strategy = GenerationType.IDENTITY)
Then, I use the simple type "long" for ID's with a lowercase l :
private long taskID;
This may be unrelated, but I also specify a different table name for my entities:
#javax.persistence.Entity(name = "Tasks")
public class Task implements Serializable
I ran into the same exception, when deploying web applications to GlassFish v3 (which uses EclipseLink as its JPA provider). I am not sure it's the same scenario as above - but the explanation for this bug in my case might help others :-) - turns out there's a bug in EclipseLink, when running under OSGi (which is the case in GlassFish), which leads EclipseLink to hold on to an "old" version of the entity class when re-deploying, resulting in this exception. The bug report is here.
As far as I know, whenever I get this error, I just re-start glassfish. Works everytime.
if you are only getting this error in junit
try adding this in persistence.xml
<jar-file>file:../classes</jar-file>
You could try and leave the definition out of the persistnce.xml The Persistence provider should than scan all classes in the classpath for #Entity annotations.
I also have to add one other item to my persistence.xml when changing class/table defs so that the EM knows to build/update tables:
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(SchemaAction='refresh')"/>
If I want a fresh start, I instead use:
<!--<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema(SchemaAction='dropDB,add')"/>
-->
I noticed that in your persistence.xml schema management is only set to "create tables" as opposed to drop/create, or update
Check the class output folder of eclipse, sometimes you change the xml and it was not updated.
The combination of deployment from within NetBeans 8.2 on Glassfish 4.1 on a Maven project with the "Debug" function of a project can cause an outdated version to be re-deployed (unclear where the fault lies).
Stop GlassFish, delete [glassfish base]/glassfish/domains/[domain name]/generated/, restart and redeploy.