[PersistenceUnit: <name>]: unable to build EntityManagerFactory - java

As stated on the subject, my problem is the EntityManagerFactory cannot be built. I am using Maven + Hibernate. I am connecting to a MySQL DB (<jdbc://mysql://localhost:3306/<dbname>).
The weird thing here is during debugging in Eclipse, it is working fine. But when I build it using Maven build, the JAR file is throwing such error. I checked the Manifest file already and all the necessary JARs were included in the Class-Path. Below is the error of the JAR displayed in the console:
===========================================================================
Feb 3, 2012 5:01:16 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Feb 3, 2012 5:01:16 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Feb 3, 2012 5:01:16 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 3, 2012 5:01:16 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 3, 2012 5:01:16 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Feb 3, 2012 5:01:16 PM class <name>.<name>.<name> <name>
SEVERE: [ERROR]: [PersistenceUnit: <name>] Unable to build EntityManagerFactory
[ERROR]: [PersistenceUnit: <name>] Unable to build EntityManagerFactory
===========================================================================
below is my persistence.xml:
<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="<name>">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>classname</class>
<properties>
<!-- <property name="hibernate.ejb.cfgfile" value="/classifyPE.cfg.xml"/> -->
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="<value>" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/<name>" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
===========================================================================
What am I doing wrong here? Or what am I lacking?
As mentioned, it's working on Debug. But when I package it into JAR,(with all the necessary JARs present in the libs folder), it's not.

add this in your xml file
<property name="javax.persistence.validation.mode">none</property>

<class>classname</class>
I suspect your entity is not named classname, so try specifying the full classpath-name (for example foo.bar.realclassname with realclassname being the name of your entity-class).

The persistence.xml file is supposed to go in the META-INF folder at the root of the jar. Check if it is there or not. I am guessing that this is purely a classpath related issue.

Try to rename your persistence unit. This is important, since the name is used to identify persistence unit related to each EntityManager.
So:
<persistence-unit name="<name>">
should be replaced with (for instance):
<persistence-unit name="myUnit">

Related

Problems with hibernate and persisence.xml

I am trying to make my first hibernate app and after running my main I get these errors:
gru 12, 2019 7:00:03 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: hibernate-dynamic
...]
gru 12, 2019 7:00:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
gru 12, 2019 7:00:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
gru 12, 2019 7:00:04 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:207)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:169)
at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:36)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:181)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:129)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:71)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at hibernate.model.Dyrektor.main(Dyrektor.java:40)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 12 more
My persistence.xml looks like this:
<?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="hibernate-dynamic" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:PUBLIC;sql.syntax_ora=true"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<!-- Hibernate properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
What can I do with it? I tried many solutions but none of them work, hope anyone could help me because it makes me very frustraded..

Unable to run basic hibernate 5 program

I am trying to run the program given in hibernate tutorial(basic).But I am facing error. Surprisingly, there are very few error logs displayed in the console. If anyone can show me where I am going wrong, I will be grateful. I have spent lot of time trying to resolve it before posting it here.
Below is my code;
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:xe;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
<property name="connection.username">hr</property>
<property name="connection.password">hr</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Event.hbm.xml
<hibernate-mapping package="org.hibernate.tutorial.hbm">
<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="increment"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
</class>
</hibernate-mapping>
Test class : NativeApiIllustrationTest
package org.hibernate.tutorial.hbm;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import junit.framework.TestCase;
public class NativeApiIllustrationTest extends TestCase {
private SessionFactory sessionFactory;
#Override
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}
#Override
protected void tearDown() throws Exception {
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
#SuppressWarnings("unchecked")
public void testBasicUsage() {
// create a couple of events...
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( new Event( "Our very first event!", new Date() ) );
session.save( new Event( "A follow up event", new Date() ) );
session.getTransaction().commit();
session.close();
// now lets pull events from the database and list them
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( "from Event" ).list();
for ( Event event : (List<Event>) result ) {
System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );
}
session.getTransaction().commit();
session.close();
}
}
Logs in console :
Jun 13, 2017 6:54:51 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Jun 13, 2017 6:54:51 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 13, 2017 6:54:51 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jun 13, 2017 6:54:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jun 13, 2017 6:54:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:#localhost:1521:xe;DB_CLOSE_DELAY=-1;MVCC=TRUE]
Jun 13, 2017 6:54:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=fod, password=****}
Jun 13, 2017 6:54:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 13, 2017 6:54:52 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Jun 13, 2017 6:54:52 AM org.hibernate.service.internal.AbstractServiceRegistryImpl stopService
INFO: HHH000369: Error stopping service [class org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] : java.lang.NullPointerException
Null pointer is coming at line : Session session = sessionFactory.openSession(); It indicates that sessionFactory is null.
Below are the jars I have added in the classpath
I
I have made some changes to the hibernate.cfg.xml and it started working.The modified xml is as below :
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="connection.username">hr</property>
<property name="connection.password">hr</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The change I done in this xml is modifying the connection url :
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>

Hibernate Driver Class Configuration Indicating Default Properties & Class

Basically I would like to know why its trying to load the org.h2.Driver even though i'm not using it and consequently throwing the error as well.
And secondly why it's using the built-in connection pool when I've specified one.
Here's a snippet of my config file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">jdbc/MobicareDB</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="generate_statistics">true</property>
And also a snippet
Of the console during application deployment
Info: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Info: HHH000412: Hibernate Core {4.3.8.Final}
Info: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Info: HHH000021: Bytecode provider name : javassist
Info: HHH000043: Configuring from resource: hibernate.cfg.xml
Info: HHH000040: Configuration resource: hibernate.cfg.xml
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Info: HHH000041: Configured SessionFactory: null
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Severe: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.h2.Driver]

Hibernate persistance.xml : Disabling contextual LOB creation as connection was null

My persistence.xml:
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.ibm.apiscanner.DTO.BaselineDTO</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.ibm.db2.jcc.DB2Driver" />
<property name="hibernate.connection.url" value="jdbc:db2://localhost:{PORT}/{DB}" />
<property name="hibernate.connection.username" value="{user}" />
<property name="hibernate.connection.password" value="{password}" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect"/>
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
I'm presented with the following:
Jan 22, 2015 9:16:48 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.DB2Dialect
Jan 22, 2015 9:16:48 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
The same url,user and password combination works when connecting via basic JDBC.
Anyone have suggestions?
That's an INFO message (nothing to worry about) because you set:
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
By default, if you don't specify this property, it will then be set to true, and a JDBC connection will be used to inspect the database metadata.
So you have two options:
You remove that property
You keep it, but you add this property as well:
hibernate.jdbc.lob.non_contextual_creation=true
but then you will get some other INFO message, telling that:
HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
It was a driver version problem for me,
-Make you have db2jcc4.jar and it is not conflicting with earlier version .
-Make sure you have specified currentschema

Configured SessionFactory: null

I have created basic hibernate application. It throw error message.
Error is:
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/crmcall/entity/CallUsers.hbm.xml
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.crmcall.entity.CallUsers -> crmcallusers
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/crmcall/entity/Customers.hbm.xml
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.crmcall.entity.Customers -> crmcustomermaster
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/crmcall/entity/User.hbm.xml
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.crmcall.entity.User -> crmusers
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.MappingException: component class not found: string
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.crmcall.util.HibernateUtil.<clinit>(HibernateUtil.java:27)
at com.crmcall.dao.UserDAO.<init>(UserDAO.java:23)
at com.crmcall.dao.UserDAO.main(UserDAO.java:36)
Caused by: org.hibernate.MappingException: component class not found: string
at org.hibernate.mapping.Component.getComponentClass(Component.java:104)
at org.hibernate.tuple.component.PojoComponentTuplizer.buildGetter(PojoComponentTuplizer.java:133)
at org.hibernate.tuple.component.AbstractComponentTuplizer.<init>(AbstractComponentTuplizer.java:43)
at org.hibernate.tuple.component.PojoComponentTuplizer.<init>(PojoComponentTuplizer.java:38)
at org.hibernate.tuple.component.ComponentEntityModeToTuplizerMapping.<init>(ComponentEntityModeToTuplizerMapping.java:52)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:50)
at org.hibernate.mapping.Component.buildType(Component.java:152)
at org.hibernate.mapping.Component.getType(Component.java:145)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.RootClass.validate(RootClass.java:193)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1102)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1287)
at com.crmcall.util.HibernateUtil.<clinit>(HibernateUtil.java:24)
... 2 more
Caused by: java.lang.ClassNotFoundException: string
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:100)
at org.hibernate.mapping.Component.getComponentClass(Component.java:101)
This is my Hibernate.cfg.xml file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.5:3306/crmtest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Enable Hibernate automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<mapping resource="com/crmcall/entity/CallUsers.hbm.xml"/>
<mapping resource="com/crmcall/entity/Customers.hbm.xml"/>
<mapping resource="com/crmcall/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is my User.hbm.xml
<hibernate-mapping>
<class name="com.crmcall.entity.User" table="crmusers">
<composite-id name="userPK" >
<key-property name="businessUnit" column="BusinessUnit" type="string"/>
<key-property name="userID" column="UserID" type="string"/>
</composite-id>
<property name="recID" >
<column name="RecID"/>
</property>
<property name="password">
<column name="Password"/>
</property>
<property name="userName">
<column name="UserName"/>
</property>
<property name="userType">
<column name="UserType"/>
</property>
<property name="userLevel">
<column name="UserLevel"/>
</property>
<property name="customerCode">
<column name="CustomerCode"/>
</property>
<property name="customerCodeson">
<column name="CustomerCodeson"/>
</property>
<property name="locationCode">
<column name="LocationCode"/>
</property>
<property name="lastUpdatedBy">
<column name="LastUpdatedBy"/>
</property>
<property name="lastUpdatedOn" type="timestamp">
<column name="LastUpdatedOn"/>
</property>
<property name="email" type="string">
<column name="Email"/>
</property>
</class>
</hibernate-mapping>
This is my calling place :
public class UserDAO {
private Session session = null;
public UserDAO() {
session = HibernateUtil.currentSession();
}
public List<User> getAllUsers() {
Transaction tn = session.beginTransaction();
List<User> users = session.createQuery("from crmusers cu order by cu.UserID").list();
System.out.println("==" + users.size());
tn.commit();
return users;
}
public static void main(String[] args){
UserDAO userDAO = new UserDAO();
userDAO.getAllUsers();
}
}
This is my project folder structre:
Please tell me what is an issue in my code?
Thanks in advance..
In User.hbm.xml you have to use type="java.lang.String" (with a big 'S'). That's it.
AS I understand the problem in your code was caused by your User.hbm.xml mapping file. To be more precised by type="string" attribute of composite-id tab.
As I understand you don't need to put type attribute obligatory so try to skip it at all; hibernate should detect it automatically. I'm not sure in last sentece because I have not used composite keys, but there are a lot of examples where peoples don't define type explicitly.
Hmmm, in your mapping file you have
<key-property name="businessUnit" column="BusinessUnit" type="string"/>
<key-property name="userID" column="UserID" type="string"/>
That should be ...type="java.lang.String"... instead, but most likely you really don't need it - Hibernate will make a (usually very good) educated guess.
Cheers,
Hibernate use the reflection to determine the mapping type at runtime.
It seems your mapping is correct, But if you still getting the same problem.
I will suggest you to remove the type attribute for the time being test, from all the String type properties such as email,businessUnit,userId
try this way for all the String type properties
<property name="email">
<column name="Email"/>
</property>
or you can try with java.lang.String also
<property name="email" type="java.lang.String">
<column name="Email"/>
</property>
Both "string" and "java.lang.String" are aliases for org.hibernate.type.StringType, so either should work in terms of naming types.
I am actually not so sure the problem is in the mapping for User. That mapping looks fine. Based on that exception I would more expect that somewhere you have
<composite-id ... class="string">
or
<component ... class="string">
or something like that.
<composite-id name="userPK" >
<key-property name="businessUnit" column="BusinessUnit" type="String"/>
<key-property name="userID" column="UserID" type="String"/>
</composite-id>
try with changing string to String

Categories