Search Results

Search found 208 results on 9 pages for 'sessionfactory'.

Page 1/9 | 1 2 3 4 5 6 7 8 9  | Next Page >

  • Hibernate SessionFactory: how to configure JNDI in Tomcat?

    - by EugeneP
    that's how the session factory should be gotten: protected SessionFactory getSessionFactory() { try { return (SessionFactory) new InitialContext() .lookup("SessionFactory"); } catch (Exception e) { } } Please provide a simple solution for Tomcat6 to be able to get SessionFactory thru simple jndi lookup in Java code. What should be written in what file on the side of Tomcat ?

    Read the article

  • Spring & Hibernate SessionFactory - recovery from a down server

    - by MJB
    So pre spring, we used version of HibernateUtil that cached the SessionFactory instance if a successful raw JDBC connection was made, and threw SQLException otherwise. This allowed us to recover from initial setup of the SessionFactory being "bad" due to authentication or server connection issues. We moved to Spring and wired things in a more or less classic way with the LocalSessionFactoryBean, the C3P0 datasource, and various dao classes which have the SessionFactory injected. Now, if the SQL server appears to not be up when the web app runs, the web app never recovers. All access to the dao methods blow up because a null sessionfactory gets injected. (once the sessionfactory is made properly, the connection pool mostly handles the up/down status of the sql server fine, so recovery is possible) Now, the dao methods are wired by default to be singletons, and we could change them to prototype. I don't think that will fix the matter though - I believe the LocalSessionFactoryBean is now "stuck" and caches the null reference (I haven't tested this yet, though, I'll shamefully admit). This has to be an issue that concerns people.

    Read the article

  • SessionFactory in Hibernate

    - by komal
    Hi, I am using hibernate-2.1 and "net.sf.hibernate.SessionFactory" class in my spring project. Now I am switched to Spring 2.5.6.A, where they are using hibernate3 and I am not able to find out the "net.sf.hibernate" package in that. But I found SessionFactory class in the package "org.springframework.orm.toplink". Is both the class one in hibernate-2.1 "net.sf.hibernate.SessionFactory" and another in "org.springframework.orm.toplink.SessionFactory" are same? Can I replace first with second one? Thanks, Komal

    Read the article

  • hibernate not picking sessionFactory

    - by Satya
    My application-context.xml is <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/myDB</value></property> <property name="username"><value>myUser</value></property> <property name="password"><value>myUser</value></property> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="mappingResources"> <property name="dataSource"><ref bean="myDataSource"/></property> <list> <value>com/x/model/config/hibernate/user.hbm.xml</value> </list> </property> <property name="hibernateProperties" > <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect </value> </property> </bean> <bean id="userdao" class="com.x.y.z.UserDao"> <property name="sessionFactory"><ref bean="mySessionFactory"/></property> </bean> </beans> user.hbm.xml is <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.cpt.model"> <class name="User" table="user"> <id name="userId" column="id"> <generator class="native"/> </id> <property name="firstname" column="firstName" /> <property name="lastName" column="lastName"/> <property name="login" column="login"/> <property name="pass" column="pass"/> <property name="superemail" column="superEmail"/> </class> </hibernate-mapping> and the UserDao is package com.x.y.z; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate.support.HibernateDaoSupport; import org.springframework.stereotype.Component; import com.x.model.User; @Component public class UserDao { private SessionFactory sessionFactory; public void addUser(User user) { Session session; try { try { session = getSessionFactory().openSession(); // session = sessionFactory.openSession(); session.save(user); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (HibernateException e) { // TODO Auto-generated catch block System.out.println("printing in the catch"); e.printStackTrace(); } } public SessionFactory getSessionFactory() { System.out.println("returning session factory ::: sessionFactory == null :: "+sessionFactory.openSession()); return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { System.out.println("this is setting session factory" + sessionFactory.getClass()); System.out.println("setting session factory ::: sessionFactory == null :: "+sessionFactory==null); this.sessionFactory = sessionFactory; System.out.println("setting session factory ::: sessionFactory == null :: "+this.sessionFactory.openSession().getClass()); System.out.println(getSessionFactory().openSession().isOpen()); } } However, I keep getting 14:45:09,929 INFO [org.hibernate.impl.SessionFactoryImpl] building session fact ory 14:45:09,933 WARN [net.sf.ehcache.config.Configurator] No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: vfs:/C:/jb /server/default/deploy/C.war/WEB-INF/lib/ehcache-1.1.jar/ehcache-failsafe.xml 14:45:10,007 INFO [org.hibernate.impl.SessionFactoryObjectFactory] Not binding factory to JNDI, no JNDI name configured 14:45:10,008 INFO [org.hibernate.impl.SessionFactoryImpl] Checking 0 named quer ies 14:45:10,017 INFO [STDOUT] this is setting session factoryclass $Proxy178 14:45:10,017 INFO [STDOUT] false 14:45:10,019 INFO [STDOUT] setting session factory ::: sessionFactory == null : : class org.hibernate.impl.SessionImpl 14:45:10,020 INFO [STDOUT] returning session factory ::: sessionFactory == null :: org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQue ue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemova ls=[] collectionUpdates=[]]) It is giving sessionFactory null . Any Idea where am I failing ? Thanks

    Read the article

  • nhibernate sessionfactory instance more than once on web service

    - by Manuel
    Hello, i have a web service that use nhibernate. I have a singleton pattern on the repositorry library but on each call the service, it creates a new instance of the session factory wich is very expensive. What can i do? region Atributos /// <summary> /// Session /// </summary> private ISession miSession; /// <summary> /// Session Factory /// </summary> private ISessionFactory miSessionFactory; private Configuration miConfiguration = new Configuration(); private static readonly ILog log = LogManager.GetLogger(typeof(NHibernatePersistencia).Name); private static IRepositorio Repositorio; #endregion #region Constructor private NHibernatePersistencia() { //miConfiguration.Configure("hibernate.cfg.xml"); try { miConfiguration.Configure(); this.miSessionFactory = miConfiguration.BuildSessionFactory(); this.miSession = this.SessionFactory.OpenSession(); log.Debug("Se carga NHibernate"); } catch (Exception ex) { log.Error("No se pudo cargar Nhibernate " + ex.Message); throw ex; } } public static IRepositorio Instancia { get { if (Repositorio == null) { Repositorio = new NHibernatePersistencia(); } return Repositorio; } } #endregion #region Propiedades /// <summary> /// Sesion de NHibernate /// </summary> public ISession Session { get { return miSession.SessionFactory.GetCurrentSession(); } } /// <summary> /// Sesion de NHibernate /// </summary> public ISessionFactory SessionFactory { get { return this.miSessionFactory; } } #endregion In wich way can i create a single instance for all services?

    Read the article

  • sessionFactory already exist

    - by senzacionale
    Can someone advice me how to prevent this error. SessionFactory already exist? sessionFactory = cfg.BuildSessionFactory(); if (sessionFactory == null) { throw new InvalidOperationException("cfg.BuildSessionFactory() returned null."); } if (sessionFactoryConfigPath != null) sessionFactories.Add(sessionFactoryConfigPath, sessionFactory);

    Read the article

  • NHibernate unable to create SessionFactory

    - by Tyler
    I'm having a bit of trouble setting up NHibernate, and I'm not too sure what the problem is exactly. I'm attempting to save a domain object to the database (Oracle 10g XE). However, I'm getting a TypeInitializationException while trying to create the ISessionFactory. Here is what my hibernate.cfg.xml looks like: <?xml version="1.0" encoding="utf-8"?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="MyProject.DataAccess"> <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property> <property name="connection.connection_string"> User ID=myid;Password=mypassword;Data Source=localhost </property> <property name="show_sql">true</property> <property name="dialect">NHibernate.Dialect.OracleDialect</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property> <mapping resource="MyProject/Domain/User.hbm.xml"/> </session-factory> </hibernate-configuration> I created a DAO which I will use to persist domain objects to the database. The DAO uses a HibernateUtil class that creates the SessionFactory. Both classes are in the DataAccess namespace along with the Hibernate configuration. This is where the exception is occuring. Here's that class: public class HibernateUtil { private static ISessionFactory SessionFactory = BuildSessionFactory(); private static ISessionFactory BuildSessionFactory() { try { // This seems to be where the problem occurs return new Configuration().Configure().BuildSessionFactory(); } catch (TypeInitializationException ex) { Console.WriteLine("Initial SessionFactory creation failed." + ex); throw new Exception("Unable to create SessionFactory."); } } public static ISessionFactory GetSessionFactory() { return SessionFactory; } } The DataAccess namespace references the NHibernate DLLs. This is virtually the same setup I've used with Hibernate in Java, so I'm not entirely sure what I'm doing wrong here. Any ideas? Edit The innermost exception is the following: "Could not find file 'C:\Users\Tyler\Documents\Visual Studio 2010\Projects\MyProject\MyProject\ConsoleApplication\bin\Debug\hibernate.cfg.xml'." ConsoleApplication contains the entry point where I've created a User object and am trying to persist it with my DAO. Why is it looking for the configuration file there? The actual persisting takes place in the DAO, which is in DataAccess. Also, when I add the configuration file to ConsoleApplication, it still does not find it.

    Read the article

  • Error creating bean with name 'sessionFactory'

    - by Sunny Mate
    hi i am getting the following exception while running my application and my applicationContext.xml is <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost/SureshDB"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> <property name="mappingResources"> <list> <value>com/jsfcompref/register/UserTa.hbm.xml</value></list> </property></bean> <bean id="UserTaDAO" class="com.jsfcompref.register.UserTaDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="UserTaService" class="com.jsfcompref.register.UserTaServiceImpl"> <property name="userTaDao"> <ref bean="UserTaDAO"/> </property> </bean> </beans> Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V any suggestion would be heplful

    Read the article

  • Hibernate Initial SessionFactory creation failed

    - by user364746
    Hello.. I'm trying to use hibernate to fill my jsf selectonemenu in ApplicationBean (in Liferay). The problem is that I got Initial SessionFactory creation failed problem. Before putting my functions in the applicationbean I was setting them in sessionbean and I got no error. For now the full error Initial SessionFactory creation failed.java.lang.ClassCastException: org.hibernate.type.StringType cannot be cast to org.hibernate.type.VersionType Thanks

    Read the article

  • Connection drop problem with Hibernate-mysql-c3p0

    - by user344788
    hi all, This is an issue which I have seen all across the web. I will bring it up again as till now I don't have a fix for the same. I am using hibernate 3. mysql 5 and latest c3p0 jar. I am getting a broken pipe exception. Following is my hibernate.cfg file. com.mysql.jdbc.Driver org.hibernate.dialect.MySQLDialect <property name="hibernate.show_sql">true</property> <property name="hibernate.use_sql_comments">true</property> <property name="hibernate.current_session_context_class">thread</property> <property name="connection.autoReconnect">true</property> <property name="connection.autoReconnectForPools">true</property> <property name="connection.is-connection-validation-required">true</property> <!--<property name="c3p0.min_size">5</property> <property name="c3p0.max_size">20</property> <property name="c3p0.timeout">1800</property> <property name="c3p0.max_statements">50</property> --><property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider </property> <property name="hibernate.c3p0.acquireRetryAttempts">30</property> <property name="hibernate.c3p0.acquireIncrement">5</property> <property name="hibernate.c3p0.automaticTestTable">C3P0TestTable</property> <property name="hibernate.c3p0.idleConnectionTestPeriod">36000</property> <property name="hibernate.c3p0.initialPoolSize">20</property> <property name="hibernate.c3p0.maxPoolSize">100</property> <property name="hibernate.c3p0.maxIdleTime">1200</property> <property name="hibernate.c3p0.maxStatements">50</property> <property name="hibernate.c3p0.minPoolSize">10</property>--> My connection pooling is occurring fine. During the day it is fine , but once i keep it idle over the night ,next day I find it giving me broken connection error. public class HibernateUtil { private static Logger log = Logger.getLogger(HibernateUtil.class); //private static Log log = LogFactory.getLog(HibernateUtil.class); private static Configuration configuration; private static SessionFactory sessionFactory; static { // Create the initial SessionFactory from the default configuration files try { log.debug("Initializing Hibernate"); // Read hibernate.properties, if present configuration = new Configuration(); // Use annotations: configuration = new AnnotationConfiguration(); // Read hibernate.cfg.xml (has to be present) configuration.configure(); // Build and store (either in JNDI or static variable) rebuildSessionFactory(configuration); log.debug("Hibernate initialized, call HibernateUtil.getSessionFactory()"); } catch (Throwable ex) { // We have to catch Throwable, otherwise we will miss // NoClassDefFoundError and other subclasses of Error log.error("Building SessionFactory failed.", ex); throw new ExceptionInInitializerError(ex); } } /** * Returns the Hibernate configuration that was used to build the SessionFactory. * * @return Configuration */ public static Configuration getConfiguration() { return configuration; } /** * Returns the global SessionFactory either from a static variable or a JNDI lookup. * * @return SessionFactory */ public static SessionFactory getSessionFactory() { String sfName = configuration.getProperty(Environment.SESSION_FACTORY_NAME); System.out.println("Current s name is "+sfName); if ( sfName != null) { System.out.println("Looking up SessionFactory in JNDI"); log.debug("Looking up SessionFactory in JNDI"); try { System.out.println("Returning new sssion factory"); return (SessionFactory) new InitialContext().lookup(sfName); } catch (NamingException ex) { throw new RuntimeException(ex); } } else if (sessionFactory == null) { System.out.println("calling rebuild session factory now"); rebuildSessionFactory(); } return sessionFactory; } /** * Closes the current SessionFactory and releases all resources. * <p> * The only other method that can be called on HibernateUtil * after this one is rebuildSessionFactory(Configuration). */ public static void shutdown() { log.debug("Shutting down Hibernate"); // Close caches and connection pools getSessionFactory().close(); // Clear static variables sessionFactory = null; } /** * Rebuild the SessionFactory with the static Configuration. * <p> * Note that this method should only be used with static SessionFactory * management, not with JNDI or any other external registry. This method also closes * the old static variable SessionFactory before, if it is still open. */ public static void rebuildSessionFactory() { log.debug("Using current Configuration to rebuild SessionFactory"); rebuildSessionFactory(configuration); } /** * Rebuild the SessionFactory with the given Hibernate Configuration. * <p> * HibernateUtil does not configure() the given Configuration object, * it directly calls buildSessionFactory(). This method also closes * the old static variable SessionFactory before, if it is still open. * * @param cfg */ public static void rebuildSessionFactory(Configuration cfg) { log.debug("Rebuilding the SessionFactory from given Configuration"); if (sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close(); if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) { log.debug("Managing SessionFactory in JNDI"); cfg.buildSessionFactory(); } else { log.debug("Holding SessionFactory in static variable"); sessionFactory = cfg.buildSessionFactory(); } configuration = cfg; } } Above is my code for the session factory. And I have only select operations . And below is the method which is used most often to execute my select queries. One tricky thing which I am not understanding is in my findById method i am using this line of code getSession().beginTransaction(); without which it gives me an error saying that this cannot happpen without a transaction. But nowhere I am closing this transaction. And thers no method to close a transaction apart from commit or rollback (as far as i know) which are not applicable for select statements. public T findById(ID id, boolean lock) throws HibernateException, DAOException { log.debug("findNyId invoked with ID ="+id+"and lock ="+lock); T entity; getSession().beginTransaction(); if (lock) entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE); else entity = (T) getSession().load(getPersistentClass(), id); return entity; } Can anyone please suggest what can I do ? I have tried out almost every solution available via googling, on stackoverlow or on hibernate forums with no avail. (And increasing wait_timeout on mysql is not a valid option in my case).

    Read the article

  • Why bind hibernate SessionFactory to a JNDI resource?

    - by jschoen
    In my current adventure of learning hibernate and setting it up to use an appserver's connection pool, most examples and resources out there point you in the direction of binding the SessionFactory to a JNDI resource in your appserver in the process. I wondering what the benefit of this is? Since the you can access a the connection pool with out doing this.

    Read the article

  • org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager

    - by BilalFromParis
    when I add the code into my spring configuration file beans-hibernate.xml <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> It doesn't work and I don't know why, can someone help me please ? My Dao Class is : public class CourseDaoImpl implements CourseDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Transactional public void store(Course course) { sessionFactory.getCurrentSession().saveOrUpdate(course); } @Transactional public void delete(Long courseId) { Course course = (Course)sessionFactory.getCurrentSession().get(Course.class, courseId); sessionFactory.getCurrentSession().delete(course); } @Transactional(readOnly=true) public Course findById(Long courseId) { return (Course)sessionFactory.getCurrentSession().get(Course.class, courseId); } @Transactional public List<Course> findAll() { Query query = sessionFactory.getCurrentSession().createQuery("FROM Course"); return (List<Course>)query.list(); } } but : juil. 04, 2012 3:38:18 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh Infos: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6ba8fb1b: startup date [Wed Jul 04 03:38:18 CEST 2012]; root of context hierarchy juil. 04, 2012 3:38:18 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions Infos: Loading XML bean definitions from class path resource [beans-hibernate.xml] juil. 04, 2012 3:38:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons Infos: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5a7fed46: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,sessionFactory,transactionManager,courseDao]; root of factory hierarchy juil. 04, 2012 3:38:19 AM org.hibernate.annotations.common.Version INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final} juil. 04, 2012 3:38:19 AM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.1.3.Final} juil. 04, 2012 3:38:19 AM org.hibernate.cfg.Environment INFO: HHH000206: hibernate.properties not found juil. 04, 2012 3:38:19 AM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist juil. 04, 2012 3:38:19 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!) juil. 04, 2012 3:38:19 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000115: Hibernate connection pool size: 20 juil. 04, 2012 3:38:19 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000006: Autocommit mode: false juil. 04, 2012 3:38:19 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000401: using driver [org.hibernate.dialect.PostgreSQLDialect] at URL [jdbc:postgresql://localhost:5432/spring] juil. 04, 2012 3:38:19 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000046: Connection properties: {user=Bilal, password=**} juil. 04, 2012 3:38:19 AM org.hibernate.dialect.Dialect INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect juil. 04, 2012 3:38:19 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 juil. 04, 2012 3:38:19 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService INFO: HHH000399: Using default transaction strategy (direct JDBC transactions) juil. 04, 2012 3:38:19 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory INFO: HHH000397: Using ASTQueryTranslatorFactory juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000228: Running hbm2ddl schema update juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000102: Fetching database metadata juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000396: Updating schema juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000261: Table found: public.course juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000037: Columns: [fee, id, title, end_date, begin_date] juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000108: Foreign keys: [] juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000126: Indexes: [course_pkey] juil. 04, 2012 3:38:19 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000232: Schema update complete juil. 04, 2012 3:38:19 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons Infos: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5a7fed46: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,sessionFactory,transactionManager,courseDao]; root of factory hierarchy juil. 04, 2012 3:38:19 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH000030: Cleaning up connection pool [jdbc:postgresql://localhost:5432/spring] Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [beans-hibernate.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/SessionFactoryImplementor at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83) at com.boutaya.bill.main.Main.main(Main.java:14) Caused by: java.lang.NoClassDefFoundError: org/hibernate/engine/SessionFactoryImplementor at org.springframework.orm.hibernate3.SessionFactoryUtils.getDataSource(SessionFactoryUtils.java:123) at org.springframework.orm.hibernate3.HibernateTransactionManager.afterPropertiesSet(HibernateTransactionManager.java:411) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ... 12 more Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.SessionFactoryImplementor at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 16 more I think the problem is when I use the Class : org.springframework.orm.hibernate3.HibernateTransactionManager ???

    Read the article

  • Error when trying to use hibernate annotations.

    - by Wilhelm
    The error I'm receiving is listed here. That's my HibernateUtil.java package com.rosejapan; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration;; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch(Throwable e) { System.err.println("Initial sessionFactory creation failed. " + e); throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } Everything looks all right... I've already included log4j-boot.jar in the CLASSPATH, but didn't resolved my problem.

    Read the article

  • how to remove the mapping resource property from hibernate.cfg file

    - by Mrityunjay
    hi, i am currently working on one project. In my project there are many entity/POJO files. currently i am using simple hibernate.cfg.xml to add all the mapping files in to the configuration like :- <mapping resource="xml/ClassRoom.hbm.xml"/> <mapping resource="xml/Teacher.hbm.xml"/> <mapping resource="xml/Student.hbm.xml"/> i am having huge number of mapping files, which makes my hibernate.cfg file looks a bit messy, so is there any way so that i do not need to add the above in to the hibernate.cfg file. rather there can be any other way to achieve the same.. please help

    Read the article

  • An item with the same key has already been added.

    - by senzacionale
    Can someone advice me how to prevent this error. An item with the same key has already been added.? // Failed to find a matching SessionFactory so make a new one. if (sessionFactory == null) { Check.Require(File.Exists(sessionFactoryConfigPath), "The config file at '" + sessionFactoryConfigPath + "' could not be found"); Configuration cfg = new Configuration(); cfg.Configure(sessionFactoryConfigPath); /*MINE*/ var persistenceModel = new PersistenceModel(); persistenceModel.AddMappingsFromAssembly(Assembly.Load("EMedicine.Core")); persistenceModel.Configure(cfg); /*END_OF_MINE*/ // Now that we have our Configuration object, create a new SessionFactory sessionFactory = cfg.BuildSessionFactory(); if (sessionFactory == null) { throw new InvalidOperationException("cfg.BuildSessionFactory() returned null."); } if (sessionFactoryConfigPath != null) sessionFactories.Add(sessionFactoryConfigPath, sessionFactory); } Error is here: sessionFactory = cfg.BuildSessionFactory();

    Read the article

  • How do I share a Hibernate SessionFactory across web applications?

    - by Jer
    I have two web applications that are running on a single Tomcat server and are connected to the same database with Hibernate. I am concerned that having two SessionFactory instances running around might cause some issues. Also, since both web applications share much of the same application logic, I thought it would be a good idea to centralize as much as I could. And since I use Spring for DI and Hibernate configuration it would make sense to have a single ApplicationContext as well. How would I go about doing something like this? Do I need to deploy a headless WAR that creates an ApplicationContext and thus a SessionFactory and allow each application access to it? Is this even a good idea?

    Read the article

  • What are the best practices to use NHiberante sessions in asp.net (mvc/web api) ?

    - by mrt181
    I have the following setup in my project: public class WebApiApplication : System.Web.HttpApplication { public static ISessionFactory SessionFactory { get; private set; } public WebApiApplication() { this.BeginRequest += delegate { var session = SessionFactory.OpenSession(); CurrentSessionContext.Bind(session); }; this.EndRequest += delegate { var session = SessionFactory.GetCurrentSession(); if (session == null) { return; } session = CurrentSessionContext.Unbind(SessionFactory); session.Dispose(); }; } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var assembly = Assembly.GetCallingAssembly(); SessionFactory = new NHibernateHelper(assembly, Server.MapPath("/")).SessionFactory; } } public class PositionsController : ApiController { private readonly ISession session; public PositionsController() { this.session = WebApiApplication.SessionFactory.GetCurrentSession(); } public IEnumerable<Position> Get() { var result = this.session.Query<Position>().Cacheable().ToList(); if (!result.Any()) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return result; } public HttpResponseMessage Post(PositionDataTransfer dto) { //TODO: Map dto to model IEnumerable<Position> positions = null; using (var transaction = this.session.BeginTransaction()) { this.session.SaveOrUpdate(positions); try { transaction.Commit(); } catch (StaleObjectStateException) { if (transaction != null && transaction.IsActive) { transaction.Rollback(); } } } var response = this.Request.CreateResponse(HttpStatusCode.Created, dto); response.Headers.Location = new Uri(this.Request.RequestUri.AbsoluteUri + "/" + dto.Name); return response; } public void Put(int id, string value) { //TODO: Implement PUT throw new NotImplementedException(); } public void Delete(int id) { //TODO: Implement DELETE throw new NotImplementedException(); } } I am not sure if this is the recommended way to insert the session into the controller. I was thinking about using DI but i am not sure how to inject the session that is opened and binded in the BeginRequest delegate into the Controllers constructor to get this public PositionsController(ISession session) { this.session = session; } Question: What is the recommended way to use NHiberante sessions in asp.net mvc/web api ?

    Read the article

  • How to make Spring load a JDBC Driver BEFORE initializing Hibernate's SessionFactory?

    - by Bill_BsB
    I'm developing a Spring(2.5.6)+Hibernate(3.2.6) web application to connect to a custom database. For that I have custom JDBC Driver and Hibernate Dialect. I know for sure that these custom classes work (hard coded stuff on my unit tests). The problem, I guess, is with the order on which things get loaded by Spring. Basically: Custom Database initializes Spring load beans from web.xml Spring loads ServletBeans(applicationContext.xml) Hibernate kicks in: shows version and all the properties correctly loaded. Hibernate's HbmBinder runs (maps all my classes) LocalSessionFactoryBean - Building new Hibernate SessionFactory DriverManagerConnectionProvider - using driver: MyCustomJDBCDriver at CustomDBURL I get a SQLException: No suitable driver found for CustomDBURL Hibernate loads the Custom Dialect My CustomJDBCDriver finally gets registered with DriverManager (log messages) SettingsFactory runs SchemaExport runs (hbm2ddl) I get a SQLException: No suitable driver found for CustomDBURL (again?!) Application get successfully deployed but there are no tables on my custom Database. Things that I tried so far: Different techniques for passing hibernate properties: embedded in the 'sessionFactory' bean, loaded from a hibernate.properties file. Nothing worked but I didn't try with hibernate.cfg.xml file neither with a dataSource bean yet. MyCustomJDBCDriver has a static initializer block that registers it self with the DriverManager. Tried different combinations of lazy initializing (lazy-init="true") of the Spring beans but nothing worked. My custom JDBC driver should be the first thing to be loaded - not sure if by Spring but...! Can anyone give me a solution for this or maybe a hint for what else I could try? I can provide more details (huge stack traces for instance) if that helps. Thanks in advance.

    Read the article

  • No Hibernate Session bound to thread exception

    - by Benchik
    I have Hibernate 3.6.0.Final and Spring 3.0.0.RELEASE I get "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" If I add the thread specification back in, I get "saveOrUpdate is not valid without active transaction" Any ideas? The spring-config.xml: <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:jsf2demo"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="sampleSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="sampleDataSource"/> <property name="annotatedClasses"> <list> <value>com.maxheapsize.jsf2demo.Book</value> </list> </property> <property name="hibernateProperties"> <props> <!-- prop key="hibernate.connection.pool_size">0</prop--> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> <!-- prop key="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop> <prop key="hibernate.current_session_context_class">thread</prop--> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean> <bean id="sampleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>org.hsqldb.jdbcDriver</value> </property> <property name="url"> <value> jdbc:hsqldb:file:/spring/db/springdb;SHUTDOWN=true </value> </property> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sampleSessionFactory"/> </bean> <bean id="daoTxTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributes"> <props> <prop key="create*"> PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED </prop> <prop key="get*"> PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED </prop> </props> </property> </bean> <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sampleSessionFactory"/> <property name="singleSession" value="true"/> </bean> <bean id="nameDao" parent="daoTxTemplate"> <property name="target"> <bean class="com.maxheapsize.dao.NameDao"> <property name="sessionFactory" ref="sampleSessionFactory"/> </bean> </property> </bean> and the DAO: public class NameDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } @Transactional @SuppressWarnings("unchecked") public List<Name> getAll() { Session session = this.sessionFactory.getCurrentSession(); List<Name> names = (List<Name>)session.createQuery("from Name").list(); return names; } //@Transactional(propagation= Propagation.REQUIRED, readOnly=false) @Transactional public void save(Name name){ Session session = this.sessionFactory.getCurrentSession(); session.saveOrUpdate(name); session.flush(); } }

    Read the article

  • Singleton constructor question

    - by gillyb
    Hi, I created a Singleton class in c#, with a public property that I want to initialize when the Singleton is first called. This is the code I wrote : public class BL { private ISessionFactory _sessionFactory; public ISessionFactory SessionFactory { get { return _sessionFactory; } set { _sessionFactory = value; } } private BL() { SessionFactory = Dal.SessionFactory.CreateSessionFactory(); } private object thisLock = new object(); private BL _instance = null; public BL Instance { get { lock (thisLock) { if (_instance == null) { _instance = new BL(); } return _instance; } } } } As far as I know, when I address the Instance BL object in the BL class for the first time, it should load the constructor and that should initialize the SessionFactory object. But when I try : BL.Instance.SessionFactory.OpenSession(); I get a Null Reference Exception, and I see that SessionFactory is null... why?

    Read the article

  • How can creating the SessionFactory become slow after updating Hibernate?

    - by DR
    In my Java SE application I used Hibernate 3.4 and creating the SessionFactory took about 5 seconds. Today I updated to Hibernate 3.5.1 and suddenly it takes over a minute. What can be the cause of such a dramatic effect? I tried different things the better part of the day and I have no clue... Some data I collected According to the profiler the most time is spent in PersisterFactory.createClassPersister and in that method ProxyFactory.createClass takes the most time. The log shows nothing unusual Changing hibernate.bytecode.use_reflection_optimizer makes no difference

    Read the article

  • Does beginTransaction in Hibernate allocate a new DB connection?

    - by illscience
    Hi folks - Just wondering if beginning a new transaction in Hibernate actually allocates a connection to the DB? I'm concerned b/c our server begins a new transaction for each request received, even if that request doesn't interact with the DB. We're seeing DB connections as a major bottleneck, so I'm wondering if I should take the time narrow the scope of my transactions. Searched everywhere and haven't been able to find a good answer. The very simple code is here: SessionFactory sessionFactory = (SessionFactory) Context.getContext().getBean("sessionFactory"); sessionFactory.getCurrentSession().beginTransaction(); sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO); thanks very much! a

    Read the article

  • Problems using HibernateTemplate: java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;

    - by user2104160
    I am quite new in Spring world and I am going crazy trying to integrate Hibernate in Spring application using HibernateTemplate abstract support class I have the following class to persist on database table: package org.andrea.myexample.HibernateOnSpring.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="person") public class Person { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int pid; private String firstname; private String lastname; public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } } Next to it I have create an interface named PersonDAO in wich I only define my CRUD method. So I have implement this interface by a class named PersonDAOImpl that also extend the Spring abstract class HibernateTemplate: package org.andrea.myexample.HibernateOnSpring.dao; import java.util.List; import org.andrea.myexample.HibernateOnSpring.entity.Person; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO{ public void addPerson(Person p) { getHibernateTemplate().saveOrUpdate(p); } public Person getById(int id) { // TODO Auto-generated method stub return null; } public List<Person> getPersonsList() { // TODO Auto-generated method stub return null; } public void delete(int id) { // TODO Auto-generated method stub } public void update(Person person) { // TODO Auto-generated method stub } } (at the moment I am trying to implement only the addPerson() method) Then I have create a main class to test the operation of insert a new object into the database table: package org.andrea.myexample.HibernateOnSpring; import org.andrea.myexample.HibernateOnSpring.dao.PersonDAO; import org.andrea.myexample.HibernateOnSpring.entity.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); System.out.println("Contesto recuperato: " + context); Person persona1 = new Person(); persona1.setFirstname("Pippo"); persona1.setLastname("Blabla"); System.out.println("Creato persona1: " + persona1); PersonDAO dao = (PersonDAO) context.getBean("personDAOImpl"); System.out.println("Creato dao object: " + dao); dao.addPerson(persona1); System.out.println("persona1 salvata nel database"); } } As you can see the PersonDAOImpl class extends HibernateTemplate so I think that it have to contain the operation of setting of the sessionFactory... The problem is that when I try to run this MainApp class I obtain the following exception: Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session; at org.springframework.orm.hibernate3.SessionFactoryUtils.doGetSession(SessionFactoryUtils.java:323) at org.springframework.orm.hibernate3.SessionFactoryUtils.getSession(SessionFactoryUtils.java:235) at org.springframework.orm.hibernate3.HibernateTemplate.getSession(HibernateTemplate.java:457) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:392) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:737) at org.andrea.myexample.HibernateOnSpring.dao.PersonDAOImpl.addPerson(PersonDAOImpl.java:12) at org.andrea.myexample.HibernateOnSpring.MainApp.main(MainApp.java:26) Why I have this problem? how can I solve it? To be complete I also insert my pom.xml containing my dependencies list: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.andrea.myexample</groupId> <artifactId>HibernateOnSpring</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>HibernateOnSpring</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Dipendenze di Spring Framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <!-- Usata da Hibernate 4 per LocalSessionFactoryBean --> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.0.RELEASE</version> </dependency> <!-- Dipendenze per AOP --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!-- Dipendenze per Persistence Managment --> <dependency> <!-- Apache BasicDataSource --> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <!-- MySQL database driver --> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.23</version> </dependency> <dependency> <!-- Hibernate --> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.1.9.Final</version> </dependency> </dependencies> </project>

    Read the article

  • org.hibernate.MappingException: Unknown entity:

    - by tsegay
    I tried to see all the questions on this topic but none of them helped me. And I really want to understand what is going on with my code. I have a standalone application which uses spring and Hibernate as JPA and I am trying to run the test using a single main Class My main class package edu.acct.tsegay.common; import edu.acct.tsegay.model.User; import edu.acct.tsegay.business.IUserBusinessObject; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { try { ApplicationContext context = new ClassPathXmlApplicationContext( "Spring3AndHibernate-servlet.xml"); IUserBusinessObject userBusinessObject = (IUserBusinessObject) context .getBean("userBusiness"); User user = (User) context.getBean("user1"); user.setPassword("pass"); user.setUsername("tsegay"); System.out.println(user.getPassword()); userBusinessObject.delete(user); User user2 = new User(); user2.setUsername("habest"); user2.setPassword("pass1"); System.out.println(user2.getPassword()); /* * userBusinessObject.save(user2); * * User user3 = userBusinessObject.searchUserbyId("tsegay"); * System.out.println("Search Result: " + user3.getUsername()); */ System.out.println("Success"); } catch (Exception e) { e.printStackTrace(); } } } my application context is: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- data source --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="test" /> <property name="password" value="password" /> </bean> <!-- session factory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- exposed person business object --> <bean id="userBusiness" class="edu.acct.tsegay.business.UserBusinessObject"> <property name="userDao" ref="userDao" /> </bean> <bean id="user1" class="edu.acct.tsegay.model.User"> <property name="username" value="tse" /> <property name="password" value="pass" /> </bean> <!-- Data Access Object --> <bean id="userDao" class="edu.acct.tsegay.dao.UserDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> My User Model is: package edu.acct.tsegay.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Version; import org.hibernate.annotations.NaturalId; @Entity public class User implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String username; private String password; private Integer VERSION; @Version public Integer getVERSION() { return VERSION; } public void setVERSION(Integer vERSION) { VERSION = vERSION; } @NaturalId public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } My DAO is: package edu.acct.tsegay.dao; import edu.acct.tsegay.model.User; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; @Repository public class UserDao implements IUserDao { private SessionFactory sessionFactory; private HibernateTemplate hibernateTemplate; public SessionFactory getSessionFactory() { return sessionFactory; } @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; this.hibernateTemplate = new HibernateTemplate(sessionFactory); } public void save(User user) { // TODO Auto-generated method stub // getHibernateTemplate().save(user); this.hibernateTemplate.save(user); } public void delete(User user) { // TODO Auto-generated method stub this.hibernateTemplate.delete(user); } public User searchUserbyId(String username) { // TODO Auto-generated method stub return this.hibernateTemplate.get(User.class, username); } } And this my stacktrace error when i run the program: pass org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: edu.acct.tsegay.model.User; nested exception is org.hibernate.MappingException: Unknown entity: edu.acct.tsegay.model.User at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679) at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:837) at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:833) at edu.acct.tsegay.dao.UserDao.delete(UserDao.java:34) at edu.acct.tsegay.business.UserBusinessObject.delete(UserBusinessObject.java:30) at edu.acct.tsegay.common.App.main(App.java:23) Caused by: org.hibernate.MappingException: Unknown entity: edu.acct.tsegay.model.User at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:580) at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1365) at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:100) at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:74) at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:793) at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:771) at org.springframework.orm.hibernate3.HibernateTemplate$25.doInHibernate(HibernateTemplate.java:843) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) ... 6 more Please let me know if you need any more of my configuration. Any help is much appreciated..

    Read the article

1 2 3 4 5 6 7 8 9  | Next Page >