Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Primi passi hibernate

16 views
Skip to first unread message

Rustichello da Pisa

unread,
Mar 1, 2009, 8:40:55 AM3/1/09
to
Ciao a tutti,
sto cercando di capire come funziona Hibernate, ahimè provo da ore
senza il minimo risultato.
Ho installato il plug-in di eclipse Hibernate Syncronizer tramite il
quale ho creato due file xml:

hibernate.cfg.xml:

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

<!-- local connection properties -->
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</
property>
<property
name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</
property>
<property name="hibernate.connection.username">angelo</property>
<property name="hibernate.connection.password">palermo</property>
<!-- property name="hibernate.connection.pool_size"></property -->

<!-- dialect for Oracle (any version) -->
<property name="dialect">org.hibernate.dialect.OracleDialect</
property>

<property name="hibernate.show_sql">false</property>
<property
name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</
property>
</session-factory>
</hibernate-configuration>

Person.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="prova">
<class
name="Person"
table="PERSON"
>
<meta attribute="sync-DAO">true</meta>
<id
name="Id"
type="integer"
column="ID"
>
<generator class="sequence"/>
</id>

<property
name="Firstname"
column="FIRSTNAME"
type="string"
not-null="true"
length="45"
/>
<property
name="Lastname"
column="LASTNAME"
type="string"
not-null="true"
length="45"
/>


</class>
</hibernate-mapping>


Da questi file xml mi vengono generate alcune classi java:

package <<prova>>
classi
-Prova;

package <<prova.base>>:
classi:
-_BaseRootDao;
-BasePerson;
-BasePersonDao;

package <<prova.dao>>:
classi:
-_RootDao;
-PersonDao;

package <<prova.dao.iface>>:
interfaccia:
PersonDao;


Per provare ho creato questa classe qui:

public class Prova {

/**
* @param args
*/
public static void main(String[] args)throws HibernateException {
// TODO Auto-generated method stub

_RootDAO.initialize();

prova.dao.iface.PersonDAO dao = new prova.dao.PersonDAO();

Person nuova = new Person(null, "Alessandro", "Del Piero");
dao.save(nuova);

}

}


Risultato:

Exception in thread "main" org.hibernate.HibernateException:
java.lang.NoClassDefFoundError: javax/transaction/Synchronization
at prova.base._BaseRootDAO.throwException(_BaseRootDAO.java:733)
at prova.base._BaseRootDAO.run(_BaseRootDAO.java:762)
at prova.base._BaseRootDAO.save(_BaseRootDAO.java:605)
at prova.base.BasePersonDAO.save(BasePersonDAO.java:109)
at Prova.main(Prova.java:20)
Caused by: java.lang.NoClassDefFoundError: javax/transaction/
Synchronization
at org.hibernate.impl.SessionImpl.<init>(SessionImpl.java:240)
at org.hibernate.impl.SessionFactoryImpl.openSession
(SessionFactoryImpl.java:503)
at org.hibernate.impl.SessionFactoryImpl.openSession
(SessionFactoryImpl.java:527)
at org.hibernate.impl.SessionFactoryImpl.openSession
(SessionFactoryImpl.java:535)
at prova.base._BaseRootDAO.getSession(_BaseRootDAO.java:64)
at prova.base._BaseRootDAO.getSession(_BaseRootDAO.java:42)
at prova.base._BaseRootDAO.run(_BaseRootDAO.java:743)
... 3 more
Caused by: java.lang.ClassNotFoundException:
javax.transaction.Synchronization
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:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 10 more


A cosa può essere dovuto il problema?
Grazie a tutti, ciao ciao.

Angelo

unread,
Mar 1, 2009, 8:46:59 AM3/1/09
to

> A cosa può essere dovuto il problema?
Ciao,
importa 'jta.jar' al tuo progetto!!

Ciao

Angelo

Piotre Ugrumov

unread,
Mar 1, 2009, 9:59:13 AM3/1/09
to

Ciao,
ho importato quel jar ed ora l'errore è questo:
Exception in thread "main" org.hibernate.MappingException: Unknown
entity: prova.Person
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister
(SessionFactoryImpl.java:580)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:
1365)
at
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId
(AbstractSaveEventListener.java:121)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId
(DefaultSaveOrUpdateEventListener.java:210)
at
org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId
(DefaultSaveEventListener.java:56)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient
(DefaultSaveOrUpdateEventListener.java:195)
at
org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate
(DefaultSaveEventListener.java:50)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate
(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546)
at prova.base._BaseRootDAO.save(_BaseRootDAO.java:619)
at prova.base._BaseRootDAO$1.run(_BaseRootDAO.java:608)
at prova.base._BaseRootDAO.run(_BaseRootDAO.java:745)


at prova.base._BaseRootDAO.save(_BaseRootDAO.java:605)
at prova.base.BasePersonDAO.save(BasePersonDAO.java:109)
at Prova.main(Prova.java:20)

Ma la classe Person esiste, eccola qui:
package prova;

import prova.base.BasePerson;

public class Person extends BasePerson {
private static final long serialVersionUID = 1L;

/*[CONSTRUCTOR MARKER BEGIN]*/
public Person () {
super();
}

/**
* Constructor for primary key
*/
public Person (java.lang.Integer id) {
super(id);
}

/**
* Constructor for required fields
*/
public Person (
java.lang.Integer id,
java.lang.String firstname,
java.lang.String lastname) {

super (
id,
firstname,
lastname);
}

/*[CONSTRUCTOR MARKER END]*/


}

Un altro dubbio nella classe PersonDao non trovo nessun metodo save ma
solo:
package prova.dao;

import org.hibernate.Session;

import prova.base.BasePersonDAO;

public class PersonDAO extends BasePersonDAO implements
prova.dao.iface.PersonDAO {

public PersonDAO () {}

public PersonDAO (Session session) {

super(session);

}

}

Mi sembra strano, non dovrebbe essere implementato il metodo save? Se
si come lo dovrei implementare?
Grazie, ciao ciao.

Angelo

unread,
Mar 1, 2009, 11:12:37 AM3/1/09
to

> si come lo dovrei implementare?
> Grazie, ciao ciao.
Non te la prendere,eh...ma i problemi che hai sono problemi che
risolvi tranquillamente leggendo/studiando i manuali sul sito di
hybernate!!!

ciao

Angelo

Piotre Ugrumov

unread,
Mar 1, 2009, 4:40:52 PM3/1/09
to

Ciao, io quella guida l'ho letta, come ne ho lette altre ma ahimè ho
capito ben poco dato che il plug-in di eclipse spezza parecchie cose.
Nella classe _BaseRootDAO è definito il save che viene chiamato, non
ho capito come sono suddivisi i vari metodi nelle classi generate in
automatico, ma il comportamente c'è.

package prova.base;

import java.io.Serializable;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.hibernate.Criteria;

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.hibernate.criterion.Expression;

import org.hibernate.criterion.Order;

public abstract class _BaseRootDAO {

public _BaseRootDAO () {}

public _BaseRootDAO (Session session) {

setSession(session);

}

protected static Map<String, SessionFactory> sessionFactoryMap;

protected SessionFactory sessionFactory;

protected Session session;

protected final static ThreadLocal<Session> currentSession = new
ThreadLocal<Session>();

/**

* Return a new Session object that must be closed when the work has
been completed.

* @return the active Session

*/

public Session getSession() {

return getSession(

getConfigurationFileName());

}

/**

* Return a new Session object that must be closed when the work has
been completed.

* @param configFile the config file must match the meta attribute
"config-file" in the hibernate mapping file

* @return the active Session

*/

protected Session getSession(String configFile) {

if (null != session && session.isOpen()) return session;

else if (null != sessionFactory) {

Session s = currentSession.get();

if (null == s || !s.isOpen()) {

s = sessionFactory.openSession();

currentSession.set(s);

}

return s;

}

else {

Session s = currentSession.get();

if (null == s || !s.isOpen()) {

s = getSessionFactory(configFile).openSession();

currentSession.set(s);

}

return s;

}

}

public void setSession (Session session) {

this.session = session;

}

/**

* Configure the session factory by reading hibernate config file

*/

public static void initialize () {

prova.dao._RootDAO.initialize(

(String) null);

}

/**

* Configure the session factory by reading hibernate config file

* @param configFileName the name of the configuration file

*/

public static void initialize (String configFileName) {

prova.dao._RootDAO.initialize(

configFileName,

prova.dao._RootDAO.getNewConfiguration(

null));

}

public static void initialize (String configFileName, Configuration
configuration) {

if (null != sessionFactoryMap && null != sessionFactoryMap.get
(configFileName)) return;

else {

if (null == configFileName) {

configuration.configure();

prova.dao._RootDAO.setSessionFactory(

null,

configuration.buildSessionFactory());

}

else {

configuration.configure(

configFileName);

prova.dao._RootDAO.setSessionFactory(

configFileName,

configuration.buildSessionFactory());

}

}

}

/**

* Set the session factory

*/

public void setSessionFactory (SessionFactory sessionFactory) {

this.sessionFactory = sessionFactory;

}

/**

* Set the session factory

*/

protected static void setSessionFactory (String configFileName,
SessionFactory sf) {

if (null == configFileName) configFileName = "";

if (null == sessionFactoryMap) sessionFactoryMap = new
HashMap<String, SessionFactory>();

sessionFactoryMap.put(

configFileName,

sf);

}

/**

* Return the SessionFactory that is to be used by these DAOs.
Change this

* and implement your own strategy if you, for example, want to pull
the SessionFactory

* from the JNDI tree.

*/

public SessionFactory getSessionFactory() {

if (null != sessionFactory) return sessionFactory;

else return getSessionFactory(

getConfigurationFileName());

}

public SessionFactory getSessionFactory(String configFileName) {

if (null == configFileName) configFileName = "";

if (null == sessionFactoryMap)

initialize(configFileName);

SessionFactory sf = (SessionFactory) sessionFactoryMap.get
(configFileName);

if (null == sf)

throw new RuntimeException("The session factory for '" +
configFileName + "' has not been initialized (or an error occured
during initialization)");

else

return sf;

}

/**

* Close all sessions for the current thread

*/

public static void closeCurrentSession () {

Session s = currentSession.get();

if (null != s) {

if (s.isOpen()) s.close();

currentSession.set(null);

}

}

/**

* Close the session

*/

public void closeSession (Session session) {

if (null != session) session.close();

}

/**

* Begin the transaction related to the session

*/

public Transaction beginTransaction(Session s) {

return s.beginTransaction();

}

/**

* Commit the given transaction

*/

public void commitTransaction(Transaction t) {

t.commit();

}

/**

* Return a new Configuration to use. This is not a mistake and is
meant

* to be overridden in the RootDAO if you want to do something
different.

* The file name is passed in so you have that to access. The config
file

* is read in the initialize method.

*/

public static Configuration getNewConfiguration (String
configFileName) {

return new Configuration();

}

/**

* Return the name of the configuration file to be used with this DAO
or null if default

*/

public String getConfigurationFileName () {

return null;

}

/**

* Return the specific Object class that will be used for class-
specific

* implementation of this DAO.

* @return the reference Class

*/

protected abstract Class getReferenceClass();

/**

* Used by the base DAO classes but here for your modification

* Get object matching the given key and return it.

*/

protected Object get(Class refClass, Serializable key) {

Session s = null;

try {

s = getSession();

return get(refClass, key, s);

} finally {

closeSession(s);

}

}

/**

* Used by the base DAO classes but here for your modification

* Get object matching the given key and return it.

*/

protected Object get(Class refClass, Serializable key, Session s) {

return s.get(refClass, key);

}

/**

* Used by the base DAO classes but here for your modification

* Load object matching the given key and return it.

*/

protected Object load(Class refClass, Serializable key) {

Session s = null;

try {

s = getSession();

return load(refClass, key, s);

} finally {

closeSession(s);

}

}

/**

* Used by the base DAO classes but here for your modification

* Load object matching the given key and return it.

*/

protected Object load(Class refClass, Serializable key, Session s) {

return s.load(refClass, key);

}

/**

* Return all objects related to the implementation of this DAO with
no filter.

*/

public java.util.List findAll () {

Session s = null;

try {

s = getSession();

return findAll(s);

}

finally {

closeSession(s);

}

}

/**

* Return all objects related to the implementation of this DAO with
no filter.

* Use the session given.

* @param s the Session

*/

public java.util.List findAll (Session s) {

return findAll(s, getDefaultOrder());

}

/**

* Return all objects related to the implementation of this DAO with
no filter.

*/

public java.util.List findAll (Order defaultOrder) {

Session s = null;

try {

s = getSession();

return findAll(s, defaultOrder);

}

finally {

closeSession(s);

}

}

/**

* Return all objects related to the implementation of this DAO with
no filter.

* Use the session given.

* @param s the Session

*/

public java.util.List findAll (Session s, Order defaultOrder) {

Criteria crit = s.createCriteria(getReferenceClass());

if (null != defaultOrder) crit.addOrder(defaultOrder);

return crit.list();

}

/**

* Return all objects related to the implementation of this DAO with
a filter.

* Use the session given.

* @param propName the name of the property to use for filtering

* @param filter the value of the filter

*/

protected Criteria findFiltered (String propName, Object filter) {

return findFiltered(propName, filter, getDefaultOrder());

}

/**

* Return all objects related to the implementation of this DAO with
a filter.

* Use the session given.

* @param propName the name of the property to use for filtering

* @param filter the value of the filter

* @param orderProperty the name of the property used for ordering

*/

protected Criteria findFiltered (String propName, Object filter,
Order order) {

Session s = null;

try {

s = getSession();

return findFiltered(s, propName, filter, order);

}

finally {

closeSession(s);

}

}

/**

* Return all objects related to the implementation of this DAO with
a filter.

* Use the session given.

* @param s the Session

* @param propName the name of the property to use for filtering

* @param filter the value of the filter

* @param orderProperty the name of the property used for ordering

*/

protected Criteria findFiltered (Session s, String propName, Object
filter, Order order) {

Criteria crit = s.createCriteria(getReferenceClass());

crit.add(Expression.eq(propName, filter));

if (null != order) crit.addOrder(order);

return crit;

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* @param name the name of a query defined externally

* @return Query

*/

protected Query getNamedQuery(String name) {

Session s = null;

try {

s = getSession();

return getNamedQuery(name, s);

} finally {

closeSession(s);

}

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the session given.

* @param name the name of a query defined externally

* @param s the Session

* @return Query

*/

protected Query getNamedQuery(String name, Session s) {

Query q = s.getNamedQuery(name);

return q;

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* @param name the name of a query defined externally

* @param param the first parameter to set

* @return Query

*/

protected Query getNamedQuery(String name, Serializable param) {

Session s = null;

try {

s = getSession();

return getNamedQuery(name, param, s);

} finally {

closeSession(s);

}

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the session given.

* @param name the name of a query defined externally

* @param param the first parameter to set

* @param s the Session

* @return Query

*/

protected Query getNamedQuery(String name, Serializable param,
Session s) {

Query q = s.getNamedQuery(name);

q.setParameter(0, param);

return q;

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the parameters given.

* @param name the name of a query defined externally

* @param params the parameter array

* @return Query

*/

protected Query getNamedQuery(String name, Serializable[] params) {

Session s = null;

try {

s = getSession();

return getNamedQuery(name, params, s);

} finally {

closeSession(s);

}

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the parameters given and the Session given.

* @param name the name of a query defined externally

* @param params the parameter array

* @s the Session

* @return Query

*/

protected Query getNamedQuery(String name, Serializable[] params,
Session s) {

Query q = s.getNamedQuery(name);

if (null != params) {

for (int i = 0; i < params.length; i++) {

q.setParameter(i, params[i]);

}

}

return q;

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the parameters given.

* @param name the name of a query defined externally

* @param params the parameter Map

* @return Query

*/

protected Query getNamedQuery(String name, Map params) {

Session s = null;

try {

s = getSession();

return getNamedQuery(name, params, s);

} finally {

closeSession(s);

}

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the parameters given and the Session given.

* @param name the name of a query defined externally

* @param params the parameter Map

* @s the Session

* @return Query

*/

protected Query getNamedQuery(String name, Map params, Session s) {

Query q = s.getNamedQuery(name);

if (null != params) {

for (Iterator i=params.entrySet().iterator(); i.hasNext(); ) {

Map.Entry entry = (Map.Entry) i.next();

q.setParameter((String) entry.getKey(), entry.getValue());

}

}

return q;

}

/**

* Execute a query.

* @param queryStr a query expressed in Hibernate's query language

* @return a distinct list of instances (or arrays of instances)

*/

public Query getQuery(String queryStr) {

Session s = null;

try {

s = getSession();

return getQuery(queryStr, s);

} finally {

closeSession(s);

}

}

/**

* Execute a query but use the session given instead of creating a
new one.

* @param queryStr a query expressed in Hibernate's query language

* @s the Session to use

*/

public Query getQuery(String queryStr, Session s) {

return s.createQuery(queryStr);

}

/**

* Execute a query.

* @param query a query expressed in Hibernate's query language

* @param queryStr the name of a query defined externally

* @param param the first parameter to set

* @return Query

*/

protected Query getQuery(String queryStr, Serializable param) {

Session s = null;

try {

s = getSession();

return getQuery(queryStr, param, s);

} finally {

closeSession(s);

}

}

/**

* Execute a query but use the session given instead of creating a
new one.

* @param queryStr a query expressed in Hibernate's query language

* @param param the first parameter to set

* @s the Session to use

* @return Query

*/

protected Query getQuery(String queryStr, Serializable param, Session
s) {

Query q = getQuery(queryStr, s);

q.setParameter(0, param);

return q;

}

/**

* Execute a query.

* @param queryStr a query expressed in Hibernate's query language

* @param params the parameter array

* @return Query

*/

protected Query getQuery(String queryStr, Serializable[] params) {

Session s = null;

try {

s = getSession();

return getQuery(queryStr, params, s);

} finally {

closeSession(s);

}

}

/**

* Execute a query but use the session given instead of creating a
new one.

* @param queryStr a query expressed in Hibernate's query language

* @param params the parameter array

* @s the Session

* @return Query

*/

protected Query getQuery(String queryStr, Serializable[] params,
Session s) {

Query q = getQuery(queryStr, s);

if (null != params) {

for (int i = 0; i < params.length; i++) {

q.setParameter(i, params[i]);

}

}

return q;

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the parameters given.

* @param queryStr a query expressed in Hibernate's query language

* @param params the parameter Map

* @return Query

*/

protected Query getQuery(String queryStr, Map params) {

Session s = null;

try {

s = getSession();

return getQuery(queryStr, params, s);

} finally {

closeSession(s);

}

}

/**

* Obtain an instance of Query for a named query string defined in
the mapping file.

* Use the parameters given and the Session given.

* @param queryStr a query expressed in Hibernate's query language

* @param params the parameter Map

* @s the Session

* @return Query

*/

protected Query getQuery(String queryStr, Map params, Session s) {

Query q = getQuery(queryStr, s);

if (null != params) {

for (Iterator i=params.entrySet().iterator(); i.hasNext(); ) {

Map.Entry entry = (Map.Entry) i.next();

q.setParameter((String) entry.getKey(), entry.getValue());

}

}

return q;

}

protected Order getDefaultOrder () {

return null;

}

/**

* Used by the base DAO classes but here for your modification

* Persist the given transient instance, first assigning a generated
identifier.

* (Or using the current value of the identifier property if the
assigned generator is used.)

*/

protected Serializable save(final Object obj) {

return (Serializable) run (

new TransactionRunnable () {

public Object run (Session s) {

return save(obj, s);

}

});

}

/**

* Used by the base DAO classes but here for your modification

* Persist the given transient instance, first assigning a generated
identifier.

* (Or using the current value of the identifier property if the
assigned generator is used.)

*/

protected Serializable save(Object obj, Session s) {

return s.save(obj);

}

/**

* Used by the base DAO classes but here for your modification

* Either save() or update() the given instance, depending upon the
value of its

* identifier property.

*/

protected void saveOrUpdate(final Object obj) {

run (

new TransactionRunnable () {

public Object run (Session s) {

saveOrUpdate(obj, s);

return null;

}

});

}

/**

* Used by the base DAO classes but here for your modification

* Either save() or update() the given instance, depending upon the
value of its

* identifier property.

*/

protected void saveOrUpdate(Object obj, Session s) {

s.saveOrUpdate(obj);

}

/**

* Used by the base DAO classes but here for your modification

* Update the persistent state associated with the given identifier.
An exception is thrown if there is a persistent

* instance with the same identifier in the current session.

* @param obj a transient instance containing updated state

*/

protected void update(final Object obj) {

run (

new TransactionRunnable () {

public Object run (Session s) {

update(obj, s);

return null;

}

});

}

/**

* Used by the base DAO classes but here for your modification

* Update the persistent state associated with the given identifier.
An exception is thrown if there is a persistent

* instance with the same identifier in the current session.

* @param obj a transient instance containing updated state

* @param s the Session

*/

protected void update(Object obj, Session s) {

s.update(obj);

}

/**

* Delete all objects returned by the query

*/

protected int delete (final Query query) {

Integer rtn = (Integer) run (

new TransactionRunnable () {

public Object run (Session s) {

return new Integer(delete((Query) query, s));

}

});

return rtn.intValue();

}

/**

* Delete all objects returned by the query

*/

protected int delete (Query query, Session s) {

List list = query.list();

for (Iterator i=list.iterator(); i.hasNext(); ) {

delete(i.next(), s);

}

return list.size();

}

/**

* Used by the base DAO classes but here for your modification

* Remove a persistent instance from the datastore. The argument may
be an instance associated with the receiving

* Session or a transient instance with an identifier associated with
existing persistent state.

*/

protected void delete(final Object obj) {

run (

new TransactionRunnable () {

public Object run (Session s) {

delete(obj, s);

return null;

}

});

}

/**

* Used by the base DAO classes but here for your modification

* Remove a persistent instance from the datastore. The argument may
be an instance associated with the receiving

* Session or a transient instance with an identifier associated with
existing persistent state.

*/

protected void delete(Object obj, Session s) {

s.delete(obj);

}

/**

* Used by the base DAO classes but here for your modification

* Re-read the state of the given instance from the underlying
database. It is inadvisable to use this to implement

* long-running sessions that span many business tasks. This method
is, however, useful in certain special circumstances.

*/

protected void refresh(Object obj, Session s) {

s.refresh(obj);

}

protected void throwException (Throwable t) {

if (t instanceof HibernateException) throw (HibernateException) t;

else if (t instanceof RuntimeException) throw (RuntimeException) t;

else throw new HibernateException(t);

}

/**

* Execute the given transaction runnable.

*/

protected Object run (TransactionRunnable transactionRunnable) {

Transaction t = null;

Session s = null;

try {

s = getSession();

t = beginTransaction(s);

Object obj = transactionRunnable.run(s);

commitTransaction(t);

return obj;

}

catch (Throwable throwable) {

if (null != t) {

try {

t.rollback();

}

catch (HibernateException e) {handleError(e);}

}

if (transactionRunnable instanceof TransactionFailHandler) {

try {

((TransactionFailHandler) transactionRunnable).onFail(s);

}

catch (Throwable e) {handleError(e);}

}

throwException(throwable);

return null;

}

finally {

closeSession(s);

}

}

/**

* Execute the given transaction runnable.

*/

protected TransactionPointer runAsnyc (TransactionRunnable
transactionRunnable) {

final TransactionPointer transactionPointer = new TransactionPointer
(transactionRunnable);

ThreadRunner threadRunner = new ThreadRunner(transactionPointer);

threadRunner.start();

return transactionPointer;

}

/**

* This class can be used to encapsulate logic used for a single
transaction.

*/

public abstract class TransactionRunnable {

public abstract Object run (Session s) throws Exception;

}

/**

* This class can be used to handle any error that has occured during
a transaction

*/

public interface TransactionFailHandler {

public void onFail (Session s);

}

/**

* This class can be used to handle failed transactions

*/

public abstract class TransactionRunnableFailHandler extends
TransactionRunnable implements TransactionFailHandler {

}

public class TransactionPointer {

private TransactionRunnable transactionRunnable;

private Throwable thrownException;

private Object returnValue;

private boolean hasCompleted = false;

public TransactionPointer (TransactionRunnable transactionRunnable)
{

this.transactionRunnable = transactionRunnable;

}

public boolean hasCompleted() {

return hasCompleted;

}

public void complete() {

this.hasCompleted = true;

}

public Object getReturnValue() {

return returnValue;

}

public void setReturnValue(Object returnValue) {

this.returnValue = returnValue;

}

public Throwable getThrownException() {

return thrownException;

}

public void setThrownException(Throwable thrownException) {

this.thrownException = thrownException;

}

public TransactionRunnable getTransactionRunnable() {

return transactionRunnable;

}

public void setTransactionRunnable(TransactionRunnable
transactionRunnable) {

this.transactionRunnable = transactionRunnable;

}

/**

* Wait until the transaction completes and return the value
returned from the run method of the TransactionRunnable.

* If the transaction throws an Exception, throw that Exception.

* @param timeout the timeout in milliseconds (or 0 for no timeout)

* @return the return value from the TransactionRunnable

* @throws TimeLimitExcededException if the timeout has been reached
before transaction completion

* @throws Throwable the thrown Throwable

*/

public Object waitUntilFinish (long timeout) throws Throwable {

long killTime = -1;

if (timeout > 0) killTime = System.currentTimeMillis() + timeout;

do {

try {

Thread.sleep(50);

}

catch (InterruptedException e) {}

}

while (!hasCompleted && ((killTime > 0 && System.currentTimeMillis
() < killTime) || killTime <= 0));

if (!hasCompleted) throw new javax.naming.TimeLimitExceededException
();

if (null != thrownException) throw thrownException;

else return returnValue;

}

}

private class ThreadRunner extends Thread {

private TransactionPointer transactionPointer;

public ThreadRunner (TransactionPointer transactionPointer) {

this.transactionPointer = transactionPointer;

}

public void run () {

Transaction t = null;

Session s = null;

try {

s = getSession();

t = beginTransaction(s);

Object obj = transactionPointer.getTransactionRunnable().run(s);

t.commit();

transactionPointer.setReturnValue(obj);

}

catch (Throwable throwable) {

if (null != t) {

try {

t.rollback();

}

catch (HibernateException e) {handleError(e);}

}

if (transactionPointer.getTransactionRunnable() instanceof
TransactionFailHandler) {

try {

((TransactionFailHandler)
transactionPointer.getTransactionRunnable()).onFail(s);

}

catch (Throwable e) {handleError(e);}

}

transactionPointer.setThrownException(throwable);

}

finally {

transactionPointer.complete();

try {

closeSession(s);

}

catch (HibernateException e) {

transactionPointer.setThrownException(e);

}

}

}

}

protected void handleError (Throwable t) {

}

}

Ora perchè l'errore:

at prova.base._BaseRootDAO.save(_BaseRootDAO.java:620)
at prova.base._BaseRootDAO$1.run(_BaseRootDAO.java:609)
at prova.base._BaseRootDAO.run(_BaseRootDAO.java:746)
at prova.base._BaseRootDAO.save(_BaseRootDAO.java:606)


at prova.base.BasePersonDAO.save(BasePersonDAO.java:109)
at Prova.main(Prova.java:20)


E' presente, mi scuso per le cose che non riesco a capire nei manuali,
faccio quello che posso.
Grazie, ciao ciao.

Piotre Ugrumov

unread,
Mar 1, 2009, 4:47:51 PM3/1/09
to

Mi sono accorto che nel file hibernate.cfg.xml mancava il riferimento
a Person.hbm.xml, che contiene il mapping alla tabella person. Ho
aggiunto il riferimento nel primo file ed ora ottengo un errore
diverso:
Exception in thread "main" org.hibernate.MappingException: invalid
configuration
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:
1521)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
at prova.base._BaseRootDAO.initialize(_BaseRootDAO.java:98)
at prova.base._BaseRootDAO.initialize(_BaseRootDAO.java:88)
at prova.base._BaseRootDAO.initialize(_BaseRootDAO.java:79)
at Prova.main(Prova.java:15)
Caused by: org.xml.sax.SAXParseException: Document is invalid: no
grammar found.
at
com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException
(ErrorHandlerWrapper.java:195)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error
(ErrorHandlerWrapper.java:131)
at
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError
(XMLErrorReporter.java:384)
at
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError
(XMLErrorReporter.java:318)
at
com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement
(XMLNSDocumentScannerImpl.java:250)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl
$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:
626)
at
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl
$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3095)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl
$PrologDriver.next(XMLDocumentScannerImpl.java:921)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next
(XMLDocumentScannerImpl.java:648)
at
com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next
(XMLNSDocumentScannerImpl.java:140)
at
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument
(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse
(XML11Configuration.java:807)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse
(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse
(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse
(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl
$JAXPSAXParser.parse(SAXParserImpl.java:522)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:
1518)
... 6 more

Mi viene detto invalid configuration, ma tutta la configurazione è
stata effettuata in automatico dal tool.
I file xml sono:
hibernate.cfg.xml:

<hibernate-configuration>
<session-factory>
<!-- local connection properties -->
<property name="hibernate.connection.url">
jdbc:oracle:thin:@localhost:1521:xe
</property>
<property name="hibernate.connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="hibernate.connection.username">angelo</property>
<property name="hibernate.connection.password">palermo</property>
<!-- property name="hibernate.connection.pool_size"></property -->
<!-- dialect for Oracle (any version) -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>

<mapping resource="hibernate.cfg.xml" />
<mapping resource="Person.hbm.xml" />
</session-factory>
</hibernate-configuration>


</class>
</hibernate-mapping>

Dove può essere l'errore?

Piotre Ugrumov

unread,
Mar 1, 2009, 5:18:06 PM3/1/09
to

Ciao,
sono riuscito a risolvere, mi sono accorto che in hibernate.cfg.xml
mancava la dichiarazione della dtd.
Ho aggiunto:


<?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">
e tutto funziona.
Grazie ancora, ciao ciao.

Manuel T

unread,
Mar 2, 2009, 6:15:22 AM3/2/09
to
Piotre Ugrumov wrote:

> Ciao,
> ho importato quel jar ed ora l'errore è questo:
> Exception in thread "main" org.hibernate.MappingException: Unknown
> entity: prova.Person

Secondo me non hai incluso il mapping di questa classe nella configurazione.

0 new messages