I am developing a java program about some lotteries of my country, it has a database with the lottos and other numbers. There is no problem with the entity classes, but when I run the problem my persistence unit does not recognize one entity class. I am a beginner in java, thanks in advance.
Here is the Numbers entity class:
#Entity
#Table(name = "NUMBERS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Numbers.findAll", query = "SELECT n FROM Numbers n")
, #NamedQuery(name = "Numbers.findById", query = "SELECT n FROM Numbers n WHERE n.id = :id")
, #NamedQuery(name = "Numbers.findByNum", query = "SELECT n FROM Numbers n WHERE n.num = :num AND n.lotto = :lotto")
, #NamedQuery(name = "Numbers.findByAssociated", query = "SELECT n FROM Numbers n WHERE n.num = :num AND n.associated = :associated AND n.lotto = :lotto")
, #NamedQuery(name = "Numbers.findByLotto", query = "SELECT n FROM Numbers n WHERE n.lotto = :lotto")})
public class Numbers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Basic(optional = false)
#Column(name = "NUM")
private int num;
#Basic(optional = false)
#Column(name = "ASSOCIATED")
private int associated;
#Basic(optional = false)
#Column(name = "LOTTO")
private String lotto;
And the code that I use to insert Numbers in the database:
public static boolean insertAlert(EntityManager em, Numbers an) {
boolean success = false;
Alert alert = Check.createAlert(Check.CONFIRMATION, "Añadir números asociados", "¿Deseas añadir estos números?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
em.getTransaction().begin();
em.persist(an);
if (em.isJoinedToTransaction()) {
em.getTransaction().commit();
System.out.println("NUMBERS SUCCESSFULLY ADDED!");
alert = Check.createAlert(Check.INFORMATION, "OK", "Números añadidos!");
alert.showAndWait();
success = true;
}
em.clear();
}
return success;
}
The 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="LotterPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>lotter.lottoClasses.Gordo</class>
<class>lotter.lottoClasses.Primitiva</class>
<class>lotter.lottoClasses.Eurojackpot</class>
<class>lotter.lottoClasses.Seis49</class>
<class>lotter.lottoClasses.Superonce</class>
<class>lotter.lottoClasses.Bonoloto</class>
<class>lotter.lottoClasses.Siete39</class>
<class>lotter.lottoClasses.Euromillones</class>
<class>lotter.Repetition</class>
<class>lotter.Numbers</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:DB;create=true"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
The persistence unit recognizes all my entity classes but not this one, I don't know how to resolve this...
Caused by: java.lang.IllegalArgumentException: Object: lotter.Numbers[ id=null ] is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at lotter.Numbers.insertAlert(Numbers.java:165)
at lotter.Numbers.insertAssociated(Numbers.java:150)
at lotter.Lotter.start(Lotter.java:41)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Exception running application lotter.Lotter
JPA Logging:
[EL Finer]: metadata: 2019-10-17 16:14:45.632--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--Searching for default mapping file in file:/Users/~/NetBeansProjects/Lotter/build/classes/ (There is no English translation for this message.)
[EL Finer]: metadata: 2019-10-17 16:14:45.643--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--Searching for default mapping file in file:/Users/~/NetBeansProjects/Lotter/build/classes/ (There is no English translation for this message.)
[EL Config]: metadata: 2019-10-17 16:14:45.803--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Bonoloto] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.825--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Euromillones] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.827--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.Repetition] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.832--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Gordo] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.833--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Seis49] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.834--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Primitiva] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.835--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Siete39] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.835--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Superonce] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.836--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The access type for the persistent class [class lotter.lottoClasses.Eurojackpot] is set to [FIELD].
[EL Config]: metadata: 2019-10-17 16:14:45.837--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Bonoloto] is being defaulted to: Bonoloto.
[EL Config]: metadata: 2019-10-17 16:14:45.868--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Euromillones] is being defaulted to: Euromillones.
[EL Config]: metadata: 2019-10-17 16:14:45.869--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.Repetition] is being defaulted to: Repetition.
[EL Config]: metadata: 2019-10-17 16:14:45.87--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Gordo] is being defaulted to: Gordo.
[EL Config]: metadata: 2019-10-17 16:14:45.871--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Seis49] is being defaulted to: Seis49.
[EL Config]: metadata: 2019-10-17 16:14:45.873--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Primitiva] is being defaulted to: Primitiva.
[EL Config]: metadata: 2019-10-17 16:14:45.874--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Siete39] is being defaulted to: Siete39.
[EL Config]: metadata: 2019-10-17 16:14:45.875--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Superonce] is being defaulted to: Superonce.
[EL Config]: metadata: 2019-10-17 16:14:45.878--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--The alias name for the entity class [class lotter.lottoClasses.Eurojackpot] is being defaulted to: Eurojackpot.
[EL Finest]: jpa: 2019-10-17 16:14:46.059--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--End predeploying Persistence Unit LotterPU; session file:/Users/user/NetBeansProjects/Lotter/build/classes/_LotterPU; state Predeployed; factoryCount 0
[EL Finer]: weaver: 2019-10-17 16:14:46.059--Thread(Thread[JavaFX Application Thread,5,main])--JavaSECMPInitializer - transformer is null.
[EL Finest]: jpa: 2019-10-17 16:14:46.059--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--Begin predeploying Persistence Unit LotterPU; session file:/Users/user/NetBeansProjects/Lotter/build/classes/_LotterPU; state Predeployed; factoryCount 0
[EL Finest]: jpa: 2019-10-17 16:14:46.059--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--End predeploying Persistence Unit LotterPU; session file:/Users/user/NetBeansProjects/Lotter/build/classes/_LotterPU; state Predeployed; factoryCount 1
[EL Finest]: jpa: 2019-10-17 16:14:46.065--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--Begin deploying Persistence Unit LotterPU; session file:/Users/user/NetBeansProjects/Lotter/build/classes/_LotterPU; state Predeployed; factoryCount 1
[EL Finer]: 2019-10-17 16:14:46.088--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--Could not initialize Validation Factory. Encountered following exception: java.lang.NoClassDefFoundError: javax/validation/Validation
[EL Finest]: properties: 2019-10-17 16:14:46.092--ServerSession(1410760993)--Thread(Thread[JavaFX Application Thread,5,main])--property=eclipselink.logging.logger; value=org.eclipse.persistence.logging.DefaultSessionLog
I had the same problem and none of the answers here fixed it.
My solution was to updated my EclipseLink version from 2.5.1 to the latest version 2.7.7 as described in this other post.
Persist only takes on entity not a list of.
So you have to iterate over the array and persist each Numbers object separately.
for (Numbers n : ans) {
em.persist(ans);
}
Common reasons for this error:
An older persistence.xml file is on the class path that doesn't
have your lotter.Numbers entry.
The class loader used to obtain the EntityManager isn't the same one
that loaded the 'an' Answer instance you are passing to the
em.persist call.
The first issue is far more common, and can be found more easily by enabling EclipseLink logging and then checking the log when it deploys the persistence unit to see what classes and mappings are loaded. Variations of it are just deploying the wrong jar, having an older jar on the class path first etc.
EclipseLink uses the class to lookup the metadata in a hash map, so if different class loaders are used, it won't find anything for it. This is a less common issue that depends on how you are loading your EntityManagerFactory and the container classloader structure. You would have problems with more then just one of your JPA entities, but it would depend on where they are coming from too.
Related
I'm trying to deploy an EAR application (includes ejb and war modules). The problem is it cannot create indexes of a foreign key in associative entity (WorkerHasRole). Every entity with relationships was created automatically in IntelliJ. I am running it on Wildfly 25.0.0. I can't figure it out even with help of the internet...
Database diagram
database screenshot
Error that occures:
03:39:20,912 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 95) MSC000001: Failed to start service jboss.persistenceunit."officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS": org.jboss.msc.service.StartException in service jboss.persistenceunit."officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS": org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
at org.jboss.as.jpa#25.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:198)
at org.jboss.as.jpa#25.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:128)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at org.wildfly.security.elytron-base#1.17.1.Final//org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:664)
at org.jboss.as.jpa#25.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:213)
at org.jboss.threads#2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads#2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
at org.jboss.threads#2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads#2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:833)
at org.jboss.threads#2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)
Caused by: org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
at org.hibernate#5.3.23.Final//org.hibernate.boot.internal.InFlightMetadataCollectorImpl.buildUniqueKeyFromColumnNames(InFlightMetadataCollectorImpl.java:2137)
at org.hibernate#5.3.23.Final//org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processJPAIndexHolders(InFlightMetadataCollectorImpl.java:2149)
at org.hibernate#5.3.23.Final//org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1671)
at org.hibernate#5.3.23.Final//org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287)
at org.hibernate#5.3.23.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1215)
at org.hibernate#5.3.23.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1246)
at org.hibernate.jipijapa-hibernate5-3#25.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa#25.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:170)
... 10 more
03:39:20,981 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 95) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'officeApplication_ear_exploded/officeApplication.war#OfficeApplicationPU'
03:39:20,981 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 95) HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
03:39:20,983 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 95) Envers integration enabled? : true
03:39:20,989 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "officeApplication_ear_exploded")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS\"" => "org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
Caused by: org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)"}}
03:39:20,990 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "officeApplication_ear_exploded")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS\"" => "org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
Caused by: org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)"}}
03:39:20,990 ERROR [org.jboss.as.server] (management-handler-thread - 1) WFLYSRV0021: Deploy of deployment "officeApplication_ear_exploded.ear" was rolled back with the following failure message:
{"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS\"" => "org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
Caused by: org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)"}}
03:39:20,990 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 95) WFLYJPA0011: Stopping Persistence Unit (phase 1 of 2) Service 'officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS'
03:39:20,991 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 25) WFLYJPA0011: Stopping Persistence Unit (phase 2 of 2) Service 'officeApplication_ear_exploded/officeApplication.war#OfficeApplicationPU'
03:39:20,991 INFO [org.hibernate.orm.beans] (ServerService Thread Pool -- 25) HHH10005004: Stopping BeanContainer : org.hibernate.resource.beans.container.internal.CdiBeanContainerExtendedAccessImpl#27593d9a
03:39:20,991 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 25) WFLYJPA0011: Stopping Persistence Unit (phase 1 of 2) Service 'officeApplication_ear_exploded/officeApplication.war#OfficeApplicationPU'
03:39:20,993 INFO [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0208: Stopped subdeployment (runtime-name: officeApplication.jar) in 2ms
03:39:21,006 INFO [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0208: Stopped subdeployment (runtime-name: officeApplication.war) in 16ms
03:39:21,006 INFO [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0028: Stopped deployment officeApplication_ear_exploded (runtime-name: officeApplication_ear_exploded.ear) in 16ms
[2021-11-13 03:39:21,025] Artifact officeApplication:ear exploded: Error during artifact deployment. See server log for details.
[2021-11-13 03:39:21,025] Artifact officeApplication:ear exploded: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"officeApplication_ear_exploded/officeApplication.jar#OfficeApplicationDS\"" => "org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
Caused by: org.hibernate.AnnotationException: Unable to create index (worker_idworker) on table worker_has_role: database column 'worker_idworker' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)"}}
The class that makes error (I will also paste Worker Class just in case)
package ejbmodule.entities;
import javax.persistence.*;
#Table(name = "worker_has_role", indexes = {
#Index(name = "fk_worker_has_role_role1_idx", columnList = "role_idrole"),
#Index(name = "fk_worker_has_role_worker1_idx", columnList = "worker_idworker")
})
#Entity
public class WorkerHasRole {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idworker_has_role", nullable = false)
private Integer id;
#ManyToOne(optional = false)
#JoinColumn(name = "role_idrole", nullable = false)
private Role roleIdrole;
#ManyToOne(optional = false)
private Worker workerIdworker;
public Worker getWorkerIdworker() {
return workerIdworker;
}
public void setWorkerIdworker(Worker workerIdworker) {
this.workerIdworker = workerIdworker;
}
public Role getRoleIdrole() {
return roleIdrole;
}
public void setRoleIdrole(Role roleIdrole) {
this.roleIdrole = roleIdrole;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence 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_2.xsd"
version="2.2">
<persistence-unit name="OfficeApplicationDS" transaction-type="JTA">
<class>ejbmodule.entities.Department</class>
<class>ejbmodule.entities.Position</class>
<class>ejbmodule.entities.WorkerId</class>
<class>ejbmodule.entities.Worker</class>
<class>ejbmodule.entities.Role</class>
<class>ejbmodule.entities.WorkerHasRole</class>
<jta-data-source>java:jboss/datasources/OfficeApplicationDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>
pom.xml of ejb
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.example</groupId>
<artifactId>officeApplication</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>ejbmodule</groupId>
<artifactId>officeApplication_EJB</artifactId>
<version>1.0-SNAPSHOT</version>
<name>officeApplication_EJB</name>
<packaging>ejb</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.7.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>8.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>javax.ejb-api</artifactId>
<version>3.2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.3.Final</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
Worker class just in case
package ejbmodule.entities;
import javax.persistence.*;
#Table(name = "workers", indexes = {
#Index(name = "fk_worker_department1_idx", columnList = "department_iddepartment"),
#Index(name = "fk_worker_position1_idx", columnList = "position_idposition")
})
#Entity
public class Worker {
#EmbeddedId
private WorkerId id;
#Column(name = "name_worker", nullable = false, length = 45)
private String nameWorker;
#Column(name = "surname_worker", nullable = false, length = 45)
private String surnameWorker;
#Column(name = "phone_worker", nullable = false, length = 9)
private String phoneWorker;
#Column(name = "email_worker", nullable = false, length = 45)
private String emailWorker;
..... list of many repetetive columns .....
public WorkerId getId() {
return id;
}
public void setId(WorkerId id) {
this.id = id;
}
}
hibernate.cfg.xml placed in project_EJB directory: main->resources->hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/officedb</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- DB schema will be updated if needed -->
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
I'm using MySQL db to persist my entities in this project. I don't get any error messages from hibernate, but when I check in the database it's empty and no tables are created.
persistence.xml (edit: datasource added and transaction-type changed to JTA)
<?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="punit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/MySqlDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
At server start:
23:42:35,136 INFO [stdout] (ServerService Thread Pool -- 59) Hibernate: drop table if exists book
23:42:35,136 INFO [stdout] (ServerService Thread Pool -- 59) Hibernate: drop table if exists hibernate_sequence
23:42:35,136 INFO [stdout] (ServerService Thread Pool -- 59) Hibernate: create table book (id bigint not null, description varchar(255), illustrations bit, nbOfPage integer, price float, title varchar(255), primary key (id))
23:42:35,137 INFO [stdout] (ServerService Thread Pool -- 59) Hibernate: create table hibernate_sequence (next_val bigint)
23:42:35,137 INFO [stdout] (ServerService Thread Pool -- 59) Hibernate: insert into hibernate_sequence values ( 1 )
At runtime after persist:
23:42:56,796 INFO [stdout] (default task-4) Hibernate: update
hibernate_sequence set next_val= ? where next_val=?
23:42:56,807 INFO [stdout] (default task-4) Book "Java book" persisted! // I print this
23:42:56,814 INFO [stdout] (default task-4) Hibernate: insert into book
(description, illustrations, nbOfPage, price, title, id) values (?, ?, ?, ?, ?, ?)
pom.xml
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<scope>provided</scope>
</dependency>
I also ran query on entity manager after persist and it returns me a list of all persisted books, but none of them are in the database.
Code as requested
Book entity:
#Entity
#NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b")
public class Book implements Serializable {
#Id #GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
private Integer nbOfPage;
private Boolean illustrations;
public Book() {
}
// getters, setters...
}
I persist entity in EJB like this:
#Named
#Stateless
public class BookEJB {
#PersistenceContext(unitName = "punit")
EntityManager em;
public Book createNewBook(Book book) {
em.persist(book);
System.out.println("Book \"" + book.getTitle() + "\" persisted!");
return book;
}
}
Update
I fixed persistence.xml, defined datasource in standalone.xml and put jdbc driver jar in server's directory following this tutorial.
But I get this exception:
23:12:11,374 INFO [org.jboss.as.jpa] (MSC service thread 1-3) WFLYJPA0002: Read persistence.xml for punit
23:12:11,625 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "MySqlDS")
]) - failure description: {"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"org.wildfly.data-source.MySqlDS is missing [jboss.jdbc-driver.mysql]",
"jboss.driver-demander.java:jboss/datasources/MySqlDS is missing [jboss.jdbc-driver.mysql]"
]}
PROBLEM SOLVED
In persistence.xml replaced <jta-data-source>jdbc/MySqlDS</jta-data-source> with <jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source> which was the correct value of jndi-name attribute of my datasource definition inside standalone.xml file.
Also I've incorrectly put module.xml and jdbc connector jar inside modules\system\layers\base\com\mysql\driver\main but instead it needs to go to
modules\system\layers\base\com\mysql\main.
Seems i've been following some other tutorial alongside with the one in my post. ^^
Lets see extracts from the JPA 2.1 specification:
8.2.1.2 transaction-type
The transaction-type attribute is used to specify whether the entity managers provided by the entity manager factory for the persistence unit must be JTA entity managers or resource-local entity managers. The value of this element is JTA or RESOURCE_LOCAL. A transaction-type of JTA assumes that a JTA data source will be provided—either as specified by the jta-data-source element or provided by the container. In general, in Java EE environments, a transaction-type of RESOURCE_LOCAL assumes that a non-JTA datasource will be provided. In a Java EE environment, if this element is not specified, the default is JTA. In a Java SE environment, if this element is not specified, the default is RESOURCE_LOCAL.
You haven't specified the transaction-type attribute in the persistence-unit element. So, according to the spec (see the highlighted part above) you have the default which is JTA.
8.2.1.5 jta-data-source, non-jta-data-source
In Java EE environments, the jta-data-source and non-jta-data-source elements are used to specify the JNDI name of the JTA and/or non-JTA data source to be used by the persistence provider. If neither is specified, the deployer must specify a JTA data source at deployment or the default JTA data source must be provided by the container, and a JTA EntityManagerFactory will be created to
correspond to it.
You haven't also specified jta-data-source element in your persistence.xml as well, and I assume you haven't specified a JTA datasource during deployment. That means the default datasource will be provided by the container (see the highlighted text in the spec).
And this datasource is not pointing to your MySQL database. The default in Wildfly, unless you reconfigured it, is H2 database. So your program might be creating and populating tables in the default database. So you need to configure a datasource in Wildfly first and specify it in the persistence.xml.
That might be the reason for:
I also ran query on entity manager after persist and it returns me a list of all persisted books, but none of them are in the database.
It seems like you insert in one db, but check another db. Could you show datasource config?
P.S. It should be comment, but not enough rating(
I am trying to insert a Employee entity into the database. I am using JPA and the database is mysql.
When I try to insert the entity, it gives me test.employee does not exist. I assume that I dont have to create
the table. Entity will automatically create the table with the annotated name.
Please find the exception and code below.
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.employee' doesn't exist
Error Code: 1146
Call: INSERT INTO employee (FIRST_NAME, LAST_NAME) VALUES (?, ?)
bind => [abc,def]
Query: InsertObjectQuery(com.example.entities.Employee#ee1ede)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
at com.example.dao.BaseDao.commitAndClose(BaseDao.java:41)
at com.example..dao.BaseDao.persist(BaseDao.java:29)
at com.example..dao.EmployeeDao.createEmployee(EmployeeDao.java:29)
at com.example.Main.main(KITMain.java:27)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.employee' doesn't exist
Error Code: 1146
Call: INSERT INTO employee (FIRST_NAME, LAST_NAME) VALUES (?, ?)
bind => [ram, mohan]
Query: InsertObjectQuerycom.example.entities.Employee#ee1ede)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:900)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:962)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:631)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1991)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:298)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:377)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:165)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:180)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:489)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:301)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:798)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1793)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1775)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1726)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:226)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:125)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4196)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1441)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1531)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:277)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1169)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:132)
... 4 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.employee' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2838)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:890)
persistence.xml
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<class>com.example.entities.Employee</class>
<properties>
<!-- derby -->
<!-- <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"
/> <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"
/> <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/test"
/> <property name="javax.persistence.jdbc.user" value="app" /> <property
name="javax.persistence.jdbc.password" value="admin" /> -->
<!-- mysql -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<!-- Configure simple SQL logging for demonstration. -->
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.logging.thread" value="false" />
<property name="eclipselink.logging.session" value="false" />
<property name="eclipselink.logging.exceptions" value="false" />
<property name="eclipselink.logging.timestamp" value="false" />
</properties>
</persistence-unit>
package com.example.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* #author ddd
*/
#Entity
#Table(name = "employee")
public class Employee implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "EMP_ID")
private String employeeId;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName ;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
[EL Config]: metadata: The access type for the persistent class [class de.allianz.kit.server.persistence.entities.Employee] is set to [FIELD].
[EL Config]: metadata: The alias name for the entity class [class de.allianz.kit.server.persistence.entities.Employee] is being defaulted to: Employee.
[EL Info]: EclipseLink, version: Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5
[EL Fine]: connection: Detected database platform: org.eclipse.persistence.platform.database.MySQLPlatform
[EL Config]: connection: Connection(3278348)--connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> "root"
datasource URL=> "jdbc:mysql://localhost:3306/test"
))
[EL Config]: connection: Connection(5863106)--Connected: jdbc:mysql://localhost:3306/test
User: root#localhost
Database: MySQL Version: 5.6.17
Driver: MySQL Connector Java Version: mysql-connector-java-5.1.30 ( Revision: alexander.soklakov#oracle.com-20140310090514-8xt1yoht5ksg2e7c )
[EL Info]: connection: file:/C:/myworkspace/kit_ws/com.example.server.persistence/classes/_kit login successful
[EL Fine]: sql: Connection(5863106)--DROP TABLE employee
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test.employee'
Error Code: 1051
Call: DROP TABLE employee
Query: DataModifyQuery(sql="DROP TABLE employee")
[EL Fine]: sql: Connection(5863106)--DROP TABLE employee
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test.employee'
Error Code: 1051
Call: DROP TABLE employee
Query: DataModifyQuery(sql="DROP TABLE employee")
[EL Fine]: sql: Connection(5863106)--DROP TABLE employee
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test.employee'
Error Code: 1051
Call: DROP TABLE employee
Query: DataModifyQuery(sql="DROP TABLE employee")
[EL Fine]: sql: Connection(5863106)--DROP TABLE employee
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test.employee'
Error Code: 1051
Call: DROP TABLE employee
Query: DataModifyQuery(sql="DROP TABLE employee")
[EL Fine]: sql: Connection(5863106)--DROP TABLE employee
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test.employee'
Error Code: 1051
Call: DROP TABLE employee
Query: DataModifyQuery(sql="DROP TABLE employee")
[EL Fine]: sql: Connection(5863106)--CREATE TABLE employee (EMP_ID VARCHAR(255) AUTO_INCREMENT NOT NULL, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), PRIMARY KEY (EMP_ID))
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Incorrect column specifier for column 'EMP_ID'
Error Code: 1063
Call: CREATE TABLE employee (EMP_ID VARCHAR(255) AUTO_INCREMENT NOT NULL, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), PRIMARY KEY (EMP_ID))
Query: DataModifyQuery(sql="CREATE TABLE employee (EMP_ID VARCHAR(255) AUTO_INCREMENT NOT NULL, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), PRIMARY KEY (EMP_ID))")
[EL Fine]: sql: Connection(5863106)--INSERT INTO employee (FIRST_NAME, LAST_NAME) VALUES (?, ?)
bind => [ram, mohan]
[EL Fine]: sql: SELECT 1
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.employee' doesn't exist
Error Code: 1146
You will need extra configuration if you want an auto generated varchar.
The generation of DDL is translating to:
CREATE TABLE employee (EMP_ID VARCHAR(255) AUTO_INCREMENT NOT NULL, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), PRIMARY KEY (EMP_ID))
and the log is saying:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Incorrect column specifier for column 'EMP_ID'
Error Code: 1063
MySql is rejecting EMP_ID becuase it cant have AUTO_INCREMENT with varchar, and you need to specify the auto generation for it. Probably Derby has this feature, and it works different for MySql.
You might wanna look in this answer.
Or just change the type of EMP_ID to an integer number if you dont mind the type or for a quick test.
Could be you mysql data is corrupted.
Go to Mysql home directory and delete all .frm extension. and restart Msysql server.
Solved.
Please have a look on my create script.
My goal is to controll the creation of the schema by script and let the dropping be handled by the metadata stuff.
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.target-database" value="DERBY" />
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
<property name="javax.persistence.schema-generation.script.action" value="create" />
<property name="javax.persistence.schema-generation.create-source" value="script" />
<property name="javax.persistence.schema-generation.create-script-source"
value="file:/home/kevin/workspace_pluginDev/zvagent/src/main/resources/META-INF/sql/create_tables.ddl" />
<property name="javax.persistence.sql-load-script-source"
value="file:/home/kevin/workspace_pluginDev/zvagent/src/main/resources/META-INF/sql/load_stammdaten.sql" />
The create script will be executed but fails on the end of the first line. It seems like the create script is executed line wise and not statement by statement:
The create script
I tested this script successfully on the same DB connection inside Eclipse using a SQL-Scrapbook editor.
CREATE TABLE TABELLENNAME (
"BESCHREIBUNG" VARCHAR(255),
"ID" BIGINT NOT NULL PRIMARY KEY,
"LASTUPDATE" BIGINT,
"SONSTIGES" VARCHAR(255),
);
But when called from JPA this happens:
Log/Error messages from the DB
[EL Fine]: sql: 2014-03-09 13:45:44.167--ServerSession(194685468)--Connection(1337157493)--Thread(Thread[main,5,main])--CREATE TABLE TABELLENNAME (
[EL Fine]: sql: 2014-03-09 13:45:44.17--ServerSession(194685468)--Thread(Thread[main,5,main])--VALUES(1)
[EL Warning]: 2014-03-09 13:45:44.172--ServerSession(194685468)--Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Syntaxfehler: Encountered "<EOF>" at line 1, column 27.
Error Code: 0
Call: CREATE TABLE TABELLENNAME (
Query: DataModifyQuery(sql="CREATE TABLE TABELLENNAME (")
[EL Fine]: sql: 2014-03-09 13:45:44.172--ServerSession(194685468)--Connection(1337157493)--Thread(Thread[main,5,main])--"BESCHREIBUNG" VARCHAR(255),
[EL Fine]: sql: 2014-03-09 13:45:44.179--ServerSession(194685468)--Thread(Thread[main,5,main])--VALUES(1)
[EL Warning]: 2014-03-09 13:45:44.181--ServerSession(194685468)--Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Syntaxfehler: Encountered "\"BESCHREIBUNG\"" at line 1, column 1.
Error Code: 0
Call: "BESCHREIBUNG" VARCHAR(255),
Query: DataModifyQuery(sql=""BESCHREIBUNG" VARCHAR(255),")
[EL Fine]: sql: 2014-03-09 13:45:44.182--ServerSession(194685468)--Connection(1337157493)--Thread(Thread[main,5,main])--"ID" BIGINT NOT NULL PRIMARY KEY,
[EL Fine]: sql: 2014-03-09 13:45:44.184--ServerSession(194685468)--Thread(Thread[main,5,main])--VALUES(1)
[EL Warning]: 2014-03-09 13:45:44.186--ServerSession(194685468)--Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Syntaxfehler: Encountered "\"ID\"" at line 1, column 1.
Error Code: 0
Call: "ID" BIGINT NOT NULL PRIMARY KEY,
Query: DataModifyQuery(sql=""ID" BIGINT NOT NULL PRIMARY KEY,")
[EL Fine]: sql: 2014-03-09 13:45:44.193--ServerSession(194685468)--Connection(1337157493)--Thread(Thread[main,5,main])--"LASTUPDATE" BIGINT,
[EL Fine]: sql: 2014-03-09 13:45:44.196--ServerSession(194685468)--Thread(Thread[main,5,main])--VALUES(1)
[EL Warning]: 2014-03-09 13:45:44.198--ServerSession(194685468)--Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Syntaxfehler: Encountered "\"LASTUPDATE\"" at line 1, column 1.
Error Code: 0
Call: "LASTUPDATE" BIGINT,
Query: DataModifyQuery(sql=""LASTUPDATE" BIGINT,")
[EL Fine]: sql: 2014-03-09 13:45:44.198--ServerSession(194685468)--Connection(1337157493)--Thread(Thread[main,5,main])--"SONSTIGES" VARCHAR(255),
[EL Fine]: sql: 2014-03-09 13:45:44.202--ServerSession(194685468)--Thread(Thread[main,5,main])--VALUES(1)
[EL Warning]: 2014-03-09 13:45:44.203--ServerSession(194685468)--Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Syntaxfehler: Encountered "\"SONSTIGES\"" at line 1, column 1.
Error Code: 0
Call: "SONSTIGES" VARCHAR(255),
Query: DataModifyQuery(sql=""SONSTIGES" VARCHAR(255),")
[EL Fine]: sql: 2014-03-09 13:45:44.204--ServerSession(194685468)--Connection(1337157493)--Thread(Thread[main,5,main])--);
[EL Fine]: sql: 2014-03-09 13:45:44.206--ServerSession(194685468)--Thread(Thread[main,5,main])--VALUES(1)
[EL Warning]: 2014-03-09 13:45:44.208--ServerSession(194685468)--Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Syntaxfehler: Encountered ")" at line 1, column 1.
Error Code: 0
Call: );
Query: DataModifyQuery(sql=");")
Q: Is there a way to format the create scripts human readable but at the same time executable as create script?
i ve a huge problem with intellij 13.0.1. I set up a JPA Project for the first time in intellij 13 and need some help to get some rid of an strange error.
Caused by: Exception [EclipseLink-4003] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Configuration error. Class [] not found.
I added a persistence Unit and add the datasource, if i test the connection it is successfull. I also added eclipselink in version 2.5.1 and postgres.jdbc.driver in 9.3-1100. I also installed Postgres # latest build. I get the error if i want to create an Entitymanager. Any idea what i could do to get rid of this error?
src:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("RoomDB");
EntityManager em = emf.createEntityManager(); //<- Configuration Error
em.getTransaction().begin();
User user1 = new User();
user1.setUsername("testuser");
user1.setPassword("testuser");
em.persist(user1);
Room room1 = new Room();
room1.setRoom_nr(12);
em.persist(room1);
em.getTransaction().commit();
em.close();
Stack-Trace:
[EL Info]: transaction: 2013-12-30 23:16:13.05--ServerSession(20030435)--property eclipselink.jdbc.user is deprecated, property javax.persistence.jdbc.user should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.062--ServerSession(20030435)--property eclipselink.jdbc.driver is deprecated, property javax.persistence.jdbc.driver should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.062--ServerSession(20030435)--property eclipselink.jdbc.url is deprecated, property javax.persistence.jdbc.url should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.062--ServerSession(20030435)--property eclipselink.jdbc.password is deprecated, property javax.persistence.jdbc.password should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.949--ServerSession(20030435)--property eclipselink.jdbc.user is deprecated, property javax.persistence.jdbc.user should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.949--ServerSession(20030435)--property eclipselink.jdbc.driver is deprecated, property javax.persistence.jdbc.driver should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.95--ServerSession(20030435)--property eclipselink.jdbc.url is deprecated, property javax.persistence.jdbc.url should be used instead.
[EL Info]: transaction: 2013-12-30 23:16:13.95--ServerSession(20030435)--property eclipselink.jdbc.password is deprecated, property javax.persistence.jdbc.password should be used instead.
[EL Info]: 2013-12-30 23:16:15.632--ServerSession(20030435)--EclipseLink, version: Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5
[EL Severe]: ejb: 2013-12-30 23:16:15.639--ServerSession(20030435)--Exception [EclipseLink-4003] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Configuration error. Class [] not found.
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4003] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Configuration error. Class [] not found.
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:766)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:182)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:527)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:140)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at de.Enviroment.main(Enviroment.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: Exception [EclipseLink-4003] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Configuration error. Class [] not found.
at org.eclipse.persistence.exceptions.DatabaseException.configurationErrorClassNotFound(DatabaseException.java:89)
at org.eclipse.persistence.sessions.DefaultConnector.loadDriverClass(DefaultConnector.java:267)
at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:85)
at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.setOrDetectDatasource(DatabaseSessionImpl.java:204)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:741)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:239)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:685)
... 13 more
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="RoomDB">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>de.Entity.Room</class>
<class>de.Entity.User</class>
<properties>
<property name="eclipselink.jdbc.url" value=""/>
<property name="eclipselink.jdbc.driver" value=""/>
<property name="eclipselink.jdbc.user" value=""/>
<property name="eclipselink.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
<property name="eclipselink.jdbc.driver" value=""/>
I'd say that's your problem. You're explicitly specifying no driver. Omit it or use org.postgresql.Driver.