Hibernate exception - java

im new to hibernate! i have followed the netbeans tutorial on creating a hibernate enabled application. after sucessfully creating a database in mysql workbench i reversed engineered the pojos etc and then tried to run a simple query(from Course) and got the following
org.hibernate.MappingException: An association from the table coursemodule refers to an unmapped class: DAL.Module
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1252)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1170)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:324)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
heres the generated class for Course
package DAL;
// Generated 02-May-2010 16:41:16 by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
/**
* Course generated by hbm2java
*/
public class Course implements java.io.Serializable {
private int id;
private String name;
private Set<Module> modules = new HashSet<Module>(0);
public Course() {
}
public Course(int id, String name) {
this.id = id;
this.name = name;
}
public Course(int id, String name, Set<Module> modules) {
this.id = id;
this.name = name;
this.modules = modules;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Module> getModules() {
return this.modules;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}
}
and its config file course.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 02-May-2010 16:41:16 by Hibernate Tools 3.2.1.GA --> <hibernate-mapping>
<class name="DAL.Course" table="course" catalog="walkthrough">
<id name="id" type="int">
<column name="id" />
<generator class="assigned" />
</id>
<property name="name" type="string">
<column name="name" not-null="true" />
</property>
<set name="modules" inverse="false" table="coursemodule">
<key>
<column name="courseId" not-null="true" unique="true" />
</key>
<many-to-many entity-name="DAL.Module">
<column name="moduleId" not-null="true" unique="true" />
</many-to-many>
</set>
</class> </hibernate-mapping>
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="Walkthrough"/>
<table-filter match-name="walkthrough"/>
<table-filter match-name="course"/>
<table-filter match-name="module"/>
<table-filter match-name="studentmodule"/>
<table-filter match-name="attendee"/>
<table-filter match-name="student"/>
<table-filter match-name="coursemodule"/>
<table-filter match-name="session"/>
<table-filter match-name="test"/>
</hibernate-reverse-engineering>
hibernate.cfg.xml
<?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="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://localhost:3306/Walkthrough</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="DAL/Student.hbm.xml"/>
<mapping resource="DAL/Walkthrough.hbm.xml"/>
<mapping resource="DAL/Test.hbm.xml"/>
<mapping resource="DAL/Module.hbm.xml"/>
<mapping resource="DAL/Session.hbm.xml"/>
<mapping resource="DAL/Course.hbm.xml"/>
</session-factory>
</hibernate-configuration>
any ideas on why im getting this exception?
ps. test is just a table with an id in it and is not related to anything. running "from Test" works
as requested heres the module.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 02-May-2010 16:41:16 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="DAL.Module" table="module" catalog="walkthrough">
<id name="id" type="int">
<column name="Id" />
<generator class="assigned" />
</id>
<property name="name" type="string">
<column name="name" not-null="true" />
</property>
<property name="studyLevel" type="int">
<column name="studyLevel" not-null="true" />
</property>
<property name="academicYear" type="int">
<column name="academicYear" not-null="true" />
</property>
<set name="courses" inverse="false" table="coursemodule">
<key>
<column name="ModuleId" not-null="true" unique="true" />
</key>
<many-to-many entity-name="DAL.Course">
<column name="CourseId" not-null="true" unique="true" />
</many-to-many>
</set>
<set name="students" inverse="false" table="studentmodule">
<key>
<column name="moduleId" not-null="true" unique="true" />
</key>
<many-to-many entity-name="DAL.Student">
<column name="studentId" not-null="true" unique="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
after running a unit test on the HibernateUtil class the test failed obtaining the session factory
getSessionFactory
03-May-2010 23:14:27 org.hibernate.cfg.annotations.Version <clinit>
INFO: Hibernate Annotations 3.3.1.GA
03-May-2010 23:14:27 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
03-May-2010 23:14:27 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
03-May-2010 23:14:27 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
03-May-2010 23:14:27 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
03-May-2010 23:14:28 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : DAL/Student.hbm.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : DAL/Walkthrough.hbm.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : DAL/Test.hbm.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : DAL/Module.hbm.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : DAL/Session.hbm.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : DAL/Course.hbm.xml
03-May-2010 23:14:28 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: DAL.Student -> student
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollection
INFO: Mapping collection: DAL.Student.modules -> studentmodule
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollection
INFO: Mapping collection: DAL.Student.sessions -> attendee
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: DAL.Walkthrough -> walkthrough
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: DAL.Test -> test
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: DAL.Module -> module
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollection
INFO: Mapping collection: DAL.Module.courses -> coursemodule
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollection
INFO: Mapping collection: DAL.Module.students -> studentmodule
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: DAL.Session -> session
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollection
INFO: Mapping collection: DAL.Session.students -> attendee
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: DAL.Course -> course
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollection
INFO: Mapping collection: DAL.Course.modules -> coursemodule
03-May-2010 23:14:29 org.hibernate.cfg.HbmBinder bindCollectionSecondPass
INFO: Mapping collection: DAL.Walkthrough.sessions -> session
03-May-2010 23:14:29 org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
03-May-2010 23:14:29 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
03-May-2010 23:14:29 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
03-May-2010 23:14:29 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
03-May-2010 23:14:29 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/Walkthrough
03-May-2010 23:14:29 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=root, password=****}
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: MySQL, version: 5.1.45-community
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} )
03-May-2010 23:14:30 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
03-May-2010 23:14:30 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
03-May-2010 23:14:30 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
03-May-2010 23:14:30 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
03-May-2010 23:14:30 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
03-May-2010 23:14:30 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
03-May-2010 23:14:32 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured

The problem is not really Course, the problem is the many-to-many association between Course and Module, the later being not recognized as a mapped class. Do you see any noticeable error messages when you create the SessionFactory? Nothing about Module? Can you show Module.hbm.xml?

Related

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>

The annotation Propagation.NEVER doesn't work

Programmers! I don't understand how doeas the propagation attribute work in the #Transactional annotation. Please, help)
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="com.springapp.mvc"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="jdbc.fetch_size">50</prop>
<prop key="hbm2ddl.auto">create-drop</prop>
</props>
</property>
<property name = "dataSource" ref = "dataSource"></property>
</bean>
Service class:
#Service
public class BookManager implements IBookManager {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void method1() {
Session session = sessionFactory.getCurrentSession();
Book book = (Book) session.load(Book.class, 1);
System.out.println("first: " + book.getTitle());
method2();
}
#Override
#Transactional(propagation = Propagation.NEVER)
public void method2() {
System.out.println("hello");
}
}
I expect that the method method2() throws an exception, as it is annotated with Propagation.NEVER. But this is not happening.
Output
июн 27, 2015 3:35:35 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
июн 27, 2015 3:35:35 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
июн 27, 2015 3:35:36 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
июн 27, 2015 3:35:36 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
июн 27, 2015 3:35:36 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#6c5945a7] of Hibernate SessionFactory for HibernateTransactionManager
Hibernate: select book0_.id as id1_0_0_, book0_.title as title2_0_0_ from books book0_ where book0_.id=?
first: 33
hello
Process finished with exit code 0
Why it doesn't work?
Thanks :)
Transactions in Spring are proxy-based: when a bean A calls a transactional bean B, it actually calls a method of a dynamic proxy, which deals with the opening of the transaction, then delegates to the actual bean B, then deals with the commit/rollback of the transaction.
If you call a method2 from a method1 of a single bean A, your call is not intercepted by the transactional proxy anymore, and Spring is thus completely unaware that method2() has been called. So nothing can check that there is no transaction.
Put the method2 in another bean, injected in BookManager, and everything will work as expected.

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]

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

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

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">

Categories