JPA EntityManagerFactory don't override persistence.xml file - jpa

When I lunch the app it is not take these properties but the default properties in glassfish-ressource.xml. I'm using JPA with nebeans automatical generated beans and entities. I want switch database at runtime.
Here his my session class
package facade;
import entities.Tpe;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
/**
*
* #author Emmanuel
*/
#Stateless
public class TpeFacade extends AbstractFacade<Tpe> {
private EntityManager em;
#Override
public EntityManager getEntityManager() {
EntityManagerFactory emf=null;
Map properties = new HashMap();
properties.put("javax.persistence.transactionType", "JTA");
properties.put("javax.persistence.jdbc.driver", "jdbc:mysql://192.20.3.81:3306/piv?zeroDateTimeBehavior=convertToNull");
properties.put("javax.persistence.jdbc.url", "com.mysql.jdbc.Driver");
properties.put("javax.persistence.jdbc.database", "piv");
properties.put("javax.persistence.jdbc.user", "username");
properties.put("javax.persistence.jdbc.password", "password");
try {
emf = Persistence.createEntityManagerFactory("ConfigurationTPEPU", properties);
System.out.println("emfznezizzhzz "+emf.getProperties() );
} catch (Exception e) {
}
em = (EntityManager) emf.createEntityManager();
return em ;
}
public TpeFacade() {
super(Tpe.class);
}
}
and my persistence file content
<?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="ConfigurationTPEPU" transaction-type="JTA">
<jta-data-source>java:app/connexion81</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>
the glassfish-ressources.xml content
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_piv_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="db1"/>
<property name="User" value="root"/>
<property name="Password" value="gsmcom"/>
<property name="URL" value="jdbc:mysql://localhost:3306/petroivoire?zeroDateTimeBehavior=convertToNull"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="java:app/connexion81" object-type="user" pool-name="mysql_piv_rootPool"/>
</resources>

You should be understood that, for an #EJB the application server is here to takes care of the inetiation of the #EJB but also the injection of the persistence.
The configuration used is that already available in the Glassfish domain (domain/config/domain.xml) and not theses properties of glassfish-ressource.xml file.
This means, for override the first config you've to use two persistences and :
switch between them programmatically (when the both are injected).
Or use Persistence.createEntityManagerFactory( jndiDataSource2NdUnitName ).createEntityManager(); where jndiDataSource2NdUnitName is the 2nd unit name.

Related

Unable to map List<String> by Hibernate in PostgreSql

I would like to do easy think - map list of String in database using hibernate.
I am able to do it when my hibernate.hbm2ddl.auto is set to create or create-drop.
If i change it to update it throws me an error during building Session Factory.
I checked that columns in db exists.
During debbuging it i found that in SchemaMigratorImpl.doMigrationToTargets Hibernate method
in field namespace primaryKey for table ITEM_POSITIONS is corrupted.
Does anyone know what i am doing wrong?
Stacktrace:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: HelloWorldPU] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:877)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:805)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at util.HibernateUtil.getEntityManagerFactory(HibernateUtil.java:43)
at TestApp.main(TestApp.java:12)
Caused by: org.hibernate.exception.SQLGrammarException: Error accessing column metadata: ITEM_POSITIONS
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.convertSQLException(InformationExtractorJdbcDatabaseMetaDataImpl.java:71)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:631)
at org.hibernate.tool.schema.extract.internal.TableInformationImpl.foreignKeys(TableInformationImpl.java:88)
at org.hibernate.tool.schema.extract.internal.TableInformationImpl.getForeignKey(TableInformationImpl.java:99)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.findMatchingForeignKey(SchemaMigratorImpl.java:338)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:318)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:157)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:59)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:129)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:97)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:481)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:802)
... 5 more
Caused by: org.postgresql.util.PSQLException: ERROR: column t1.tgconstrname does not exists
Pozycja: 113
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254)
at org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData.getImportedExportedKeys(AbstractJdbc2DatabaseMetaData.java:3373)
at org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData.getImportedKeys(AbstractJdbc2DatabaseMetaData.java:3566)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:580)
... 16 more
Configuration:
Java 8
PostgreSql: postgresql-12.1-3-windows-x64
pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>hibernatemapping</groupId>
<artifactId>hibernatemapping</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.0.Final</version>
</dependency>
</dependencies>
</project>
persistence.xml:
<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_2_1.xsd">
<persistence-unit name="HelloWorldPU">
<class>domain.Item</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/hibernate_db?useSSL=false"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
HibernateUtil Class which is responsible for creating EntityManager:
package util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static EntityManagerFactory entityManagerFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.postgresql.Driver");
settings.put(Environment.URL, "jdbc:postgresql://localhost:5432/hibernate_db?useSSL=false");
settings.put(Environment.USER, "postgres");
settings.put(Environment.PASS, "admin");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "auto-update");
configuration.setProperties(settings);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
public static EntityManagerFactory getEntityManagerFactory(){
if (entityManagerFactory == null) {
entityManagerFactory = Persistence.createEntityManagerFactory("HelloWorldPU");
}
return entityManagerFactory;
}
}
Entity class:
package domain;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.*;
import javax.persistence.Entity;
import javax.persistence.*;
import java.util.*;
#Entity
public class Item {
#Id
#GeneratedValue(generator = "ID_GENERATOR")
#GenericGenerator(name = "ID_GENERATOR",
strategy = "enhanced-sequence",
parameters = {
#Parameter(name = "sequence_name",
value = "Item_sequence")
})
private Long id;
private String name;
#ElementCollection
#CollectionTable(name = "ITEM_POSITIONS")
#OrderColumn
#Column(name = "POSITIONS")
protected List<String> positions = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPositions() {
return positions;
}
public void setPositions(List<String> positions) {
this.positions = positions;
}
}
Test class:
import domain.Item;
import util.HibernateUtil;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import java.util.ArrayList;
import java.util.List;
public class TestApp {
public static void main(String[] args){
EntityManagerFactory emf = HibernateUtil.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Item item = new Item();
item.setName("Item1");
List<String> positions = new ArrayList<>();
positions.add("Position1");
positions.add("Position2");
positions.add("Position3");
positions.add("Position4");
positions.add("Position5");
item.setPositions(positions);
em.persist(item);
transaction.commit();
em.close();
emf.close();
}
}
How to reproduce:
Run with property name="hibernate.hbm2ddl.auto" value="create"
Run with property name="hibernate.hbm2ddl.auto" value="update"
Set breakpoint in QueryExecutorImpl.receiveErrorResponse
Search invocation stack for SchemaMigratorImpl.doMigrationToTargets
I solved this issue.
I added this line to my pertsistence.xml
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
And i changed driver to:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>

Unable to build entity manager factory - Rest Tomcat Jpa

I'm making a Restful web service using netbeans, tomcat, jpa and jax-rs. I have this error since I've add the <class /> tags to my persistence.xml for all of my classes (And I need them to make a select).
The error is : https://gist.github.com/anonymous/bb37c28cdb3dbdf721c5206bfa6369c3
And my persistence.xml is :
<?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="NataRestServicePU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>model.Media</class>
<class>model.MediaTypeDB</class>
<class>model.Message</class>
<class>model.Observation</class>
<class>model.Session</class>
<class>model.Species</class>
<class>model.User</class>
<class>model.UserType</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3307/natagora?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
And this is the main dao (that worked before, didn't change anything) but without all the CRUD methods (just the read for example)
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
public class MainDAO<T> implements IMainDAO<T> {
protected Class<T> clazz;
private final EntityManagerFactory factory;
private static final String PERSISTENCE_UNIT_NAME = "NataRestServicePU";
#PersistenceContext(unitName = "NataRestServicePU")
protected EntityManager entityManager;
public MainDAO(Class<T> type){
clazz = type;
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
#Override
public T read(int id){
try{
newEntityManager();
return entityManager.find(clazz,id);
}finally{
closeEntityManager();
}
}
protected void closeEntityManager(){
entityManager.close();
}
protected void newEntityManager(){
entityManager = factory.createEntityManager();
}
}

Get Date of Database with JPQL

I have the next code:
package co.com.patios.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
public class Date {
private java.util.Date dateActual;
#Id
#Column(name = "date")
#Temporal(TemporalType.DATE)
public java.util.Date getDateActual() {
return dateActual;
}
public void setDateActual(java.util.Date dateActual) {
this.dateActual = dateActual;
}
}
<?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="PatiosDS">
<jta-data-source>java:jboss/datasources/PatiosDS</jta-data-source>
<class>co.com.patios.entity.Date</class>
<class>co.com.patios.entity.EntradaVehiculoPatio</class>
<class>co.com.patios.entity.EstadoVehiculo</class>
<class>co.com.patios.entity.MarcaVehiculo</class>
<class>co.com.patios.entity.ModeloVehiculo</class>
<class>co.com.patios.entity.Patio</class>
<class>co.com.patios.entity.Usuario</class>
<class>co.com.patios.entity.Vehiculo</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.default_schema" value="public" />
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
</properties>
</persistence-unit>
My problem is the annotation #Entity, that show the next message
Table "Date" cannot be resolved
where I have the next line "co.com.patios.entity.Date" in the my file persistence.xml
I want to know, what could be the problem ?
Note: The code run correct, but show the message
Table "Date" cannot be resolved
and it show in eclipse like error

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

I have a problem with Java Persistence API and Hibernate.
My situation of project is:
My persistence.xml file is:
<persistence
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"
version="2.0">
<persistence-unit name="JPA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.david.Libro</class>
<class>com.david.Categoria</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="javax.persistence.transactionType" value="RESOURCE_LOCAL" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/arquitecturaJava" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>
And i create EntityManagerFactory in:
private static EntityManagerFactory buildEntityManagerFactory()
{
try
{
return Persistence.createEntityManagerFactory("JPA");
}
catch (Throwable ex)
{
ex.printStackTrace();
//throw new RuntimeException("Error al crear la factoria de JPA:->"+ ex.getMessage());
}
}
My error is about create EntityManagerFactory:
javax.persistence.PersistenceException: [PersistenceUnit: JPA] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.david.JPAHelper.buildEntityManagerFactory(JPAHelper.java:14)
at com.david.JPAHelper.<clinit>(JPAHelper.java:8)
at com.david.Categoria.buscarTodos(Categoria.java:93)
at com.david.FormularioInsertarLibroAccion.ejecutar(FormularioInsertarLibroAccion.java:25)
at com.david.ControladorLibros.doGet(ControladorLibros.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.david.Libro
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2638)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:706)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3512)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3466)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1355)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 27 more
Part of Libro and Categoria classes code is:
#Entity
#Table(name = "Categorias")
public class Categoria implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "categoria")
private String id;
private String descripcion;
....
and
#Entity
#Table(name="Libros")
public class Libro implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
private String isbn;
private String titulo;
#ManyToOne
#JoinColumn (name="categoria")
private Categoria categoria;
....
My file of Hibernate Configuration is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/arquitecturajava</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">5</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<mapping class="com.david.Categoria"></mapping>
<mapping class="com.david.Libro"></mapping>
</session-factory>
</hibernate-configuration>
Any ideas!!
ThankĀ“s!!
You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?
But as the other answer also pointed out, this is not okay like this:
#Id
#JoinColumn(name = "categoria")
private String id;
Didn't you want to use #Column instead?
Suppress the #JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.
Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory
** This is a solution if you are using Audit table.#Audit
Use:- #Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>

Why could <exclude-unlisted-classes>false</exclude-unlisted-classes> fail to work?

With this persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence 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"
version="1.0">
<persistence-unit name="ODP_Server_Test"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ODPServerDataSource)</non-jta-data-source> -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:unit-testing;create=true" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.target-database" value="DERBY" />
</properties>
</persistence-unit>
</persistence>
and a simple test:
public class RepositoryTest {
private static Logger logger = LoggerFactory
.getLogger(RepositoryTest.class);
private static EntityManagerFactory emf;
private EntityManager em;
private RepositoryImpl repo = new RepositoryImpl();
#BeforeClass
public static void setUp() {
try {
logger.info("Starting in-memory DB for unit tests");
#SuppressWarnings("unused")
Class<?> cls = org.apache.derby.jdbc.EmbeddedDriver.class;
DriverManager.getConnection(
"jdbc:derby:memory:unit-testing;create=true").close();
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during database startup.");
}
try {
logger.info("Building JPA EntityManager for unit tests");
emf = Persistence.createEntityManagerFactory("ODP_Server_Test");
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager instantiation.");
}
}
#AfterClass
public static void tearDown() throws SQLException {
logger.info("Shutting down JPA");
if (emf != null) {
emf.close();
}
try {
DriverManager.getConnection(
"jdbc:derby:memory:unit-testing;drop=true").close();
} catch (SQLException ex) {
if (ex.getSQLState().equals("08006")) {
logger.info("DB shut down");
} else {
throw ex;
}
}
fail("DB didn't shut down");
}
#Before
public void setEM() {
em = emf.createEntityManager();
repo.setEntityManager(em);
}
#After
public void flushEM() {
if (em != null) {
em.flush();
em.close();
em = null;
}
}
#Test
public void noBlocksInEmptyDB() {
assertThat(repo.findFunBlock(1), is((FunctionalBlock) null));
}
}
I get
[EL Warning]: 2012-04-17 15:08:18.476--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
After replacing <exclude-unlisted-classes>false</exclude-unlisted-classes> with a lot of <class> elements, the problem can be fixed, but I'd prefer not to have to remember to edit persistence.xml every time I need to add a new entity or remove an old one. Why doesn't the version with <exclude-unlisted-classes> work?
I had faced similar situation
If I generate JPA metamodel, copy paste it in correct pacakge and check it in to svn, and disable metamodel generation, all junit tests were fine
if i generate metamodel with every build, at junit time - embedded glassfish will find all ejb and metamodel fine, but non ejb junit will fail
I had to do this in my src/test/resources/META-INF/persistence.xml
<persistence-unit name="test-xxx" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jar-file>file:../classes</jar-file>
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.oracle.Oracle11Platform"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="JavaLogger"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#localhost:1521:xxx"/>
<property name="javax.persistence.jdbc.password" value="xxx"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="javax.persistence.jdbc.user" value="xxx"/>
</properties>
</persistence-unit>