Search Results

Search found 2391 results on 96 pages for 'hibernate'.

Page 6/96 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Confusion between JPA and Hibernate cascading

    - by Jay
    I'm using Hibernate 3.6 and have my code annotated (versus using hibernate mapping files). I ran into the known "problem" of using JPA cascading options that are not compatible with Hibernate's CascadeType (see this link for more info http://www.mkyong.com/hibernate/cascade-jpa-hibernate-annotation-common-mistake/). I was hoping to get a bit more clarification on the problem. I have some particular questions: 1) So @Cascade({CascadeType.SAVE_UPDATE}) works for saveOrUpdate(), but does it apply also if I use merge() or persist()? or do I have to use all three Hibernate CascadeTypes? 2) How do I decide whether to use JPA cascade options or the Hibernate @Cascade annotation instead? 2) There is a "bug" filed against this in Hibernate, but the developers apparently see this as a documentation issue, (I'm completely disagree with them), and I'm not seeing that it was addressed in said documentation. Anyone know why this is "working as designed" and not a bug in Hibernate's JPA implementation? Many thanks in advance.

    Read the article

  • Spring & hibernate configuration (using maven): java.lang.ClassNotFoundException: org.hibernate.cfg.

    - by Marcos Carceles
    Hi, I am trying to include spring and hibernate in an application running on a Weblogic 10.3 server. When I run the application in the server, while accessing an TestServlet to check my configuration I get the following exception: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in class path resource [spring-config/HorizonModelPeopleConnectionsSpringContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org.hibernate.cfg.Configuration at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:448) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:284) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:91) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:75) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:65) at view.com.horizon.test.SpringHibernateServlet.doGet(SpringHibernateServlet.java:27) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292) at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at oracle.security.wls.filter.SSOSessionSynchronizationFilter.doFilter(SSOSessionSynchronizationFilter.java:279) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at oracle.dms.wls.DMSServletFilter.doFilter(DMSServletFilter.java:326) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3592) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2202) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2108) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1432) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201) at weblogic.work.ExecuteThread.run(ExecuteThread.java:173) Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org.hibernate.cfg.Configuration at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:100) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:756) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:721) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:384) ... 31 more Caused by: java.lang.NoClassDefFoundError: org.hibernate.cfg.Configuration at org.springframework.orm.hibernate3.LocalSessionFactoryBean.class$(LocalSessionFactoryBean.java:158) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.(LocalSessionFactoryBean.java:158) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:85) ... 35 more I have checked my application and the hibernate jar file is included and it contains the class it says its missing: org.hibernate.cfg.Configuration. The application is built with maven. These are the dependencies of the JAR file using spring and hibernate: <!-- Frameworks --> <!-- Hibernate framework --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.7.ga</version> </dependency> <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.2</version> </dependency> <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.4.GA</version> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>2.5.6</version> </dependency> At first I thought it could be an issue with the versions in the spring and hibernate libraries, so I have tried with different ones, but still I couldn't find anywhere where it says which library versions are compatible,. just got that Spring 2.5.x needs hibernate =3.1 And this is my Spring config file: <?xml version="1.0" encoding="UTF-8"?> <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"> <bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>jdbc/WebCenterDS</value> </property> <!--property name="resourceRef"> <value>true</value> </property> <property name="jndiEnvironment"> <props> <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop> <prop key="java.naming.provider.url">t3://localhost:7001</prop> </props> </property--> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="configLocation"> <value>classpath:hibernate-config/hibernate.cfg.xml</value> </property> <property name="mappingResources"> <list> <value>classpath:com/horizon/model/peopleconnections/profile/internal/bean/CustomAttribute.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value> </property> </bean> <bean id="profileExtensionDAO" class="com.horizon.model.peopleconnections.profile.internal.dao.ProfileExtensionDAOImpl"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> </beans> The WAR structure I get is the following: J2EETestApplication ¦ springhibernate.jsp ¦ +---WEB-INF ¦ faces-config.xml ¦ web.xml ¦ weblogic.xml ¦ +---classes ¦ +---view ¦ +---com ¦ +---horizon ¦ +---test ¦ SpringHibernateServlet.class ¦ +---lib activation-1.1.jar antlr-2.7.6.jar aopalliance-1.0.jar asm-1.5.3.jar asm-attrs-1.5.3.jar cglib-2.1_3.jar commons-codec-1.3.jar commons-collections-2.1.1.jar commons-logging-1.1.1.jar dom4j-1.6.1.jar ehcache-1.2.3.jar hibernate-3.2.7.ga.jar horizon-model-commons-1.0-SNAPSHOT.jar horizon-model-peopleconnections-1.0-SNAPSHOT.jar horizon-shared-commons-1.0-SNAPSHOT.jar horizon-shared-logging-1.0-SNAPSHOT.jar horizon-shared-util-1.0-SNAPSHOT.jar horizon-shared-webcenter-1.0-SNAPSHOT.jar horizon-shared-webcenter.jar httpclient-4.0.1.jar httpcore-4.0.1.jar javassist-3.4.GA.jar jta-1.0.1B.jar log4j-1.2.14.jar mail-1.4.1.jar peopleconnections-profile-model-11.1.1.2.0.jar saxon-9.1.0.8.jar serviceframework-11.1.1.2.0.jar slf4j-api-1.5.2.jar slf4j-log4j12-1.5.2.jar spring-beans-2.5.6.jar spring-context-2.5.6.jar spring-core-2.5.6.jar spring-orm-2.5.6.jar spring-tx-2.5.6.jar Is there any dependency or configuration I am missing? If I use hibernate without spring I don't get the ClassDefNotFoundException.

    Read the article

  • WiFi can't reconnect after suspend/hibernate on Ubuntu 12.04.1

    - by CyberOPS
    I've had this problem since Ubuntu 11.10 (my first install) but I was able to get around this issue with this answer. When I updated to Ubuntu 12.04 I encrypted the home folder, so I wasn't able to suspend or hibernate anymore (disappointing :l). Because of this and another issue I had1, I chose to reinstall. Sometime after I reinstalled, I was reminded about reconnection issue because it wasn't working after I suspended. I tried to use the same fix as before but I couldn't get it to work. I've also tried a couple other different fixes I found around the web but they didn't work. Since I'm new to linux, I'm gonna have a tough time figuring this out by myself. So does anyone know how, or what I need to figure out how, to fix this? Info: Computer: HP Pavilion dv6t-6b00 CTO Quad Edition Entertainment Notebook PC Network Card: Intel® Centrino® Wireless-N 1000 OS: Ubuntu 12.04.1 (x64) dual booting with Windows 7 (x64) (Not using Wubi) Wireless Card Driver: Intel Wireless WiFi Link drivers for Linux (iwlwifi) 1 - ntfs-config caused colord to crash on startup, even after NTFS-Config was removed.

    Read the article

  • Persist subclass as superclass using Hibernate

    - by franziga
    I have a subclass and a superclass. However, only the fields of the superclass are needed to be persist. session.saveOrUpdate((Superclass) subclass); If I do the above, I will get the following exception. org.hibernate.MappingException: Unknown entity: test.Superclass at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:628) at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1366) at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:203) at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:535) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:103) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:527) at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:523) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342) at $Proxy54.saveOrUpdate(Unknown Source) How can I persist a subclass as a superclass? I do not prefer creating a superclass instance and then passing the values from the subclass instance. Because, it is easy to forget updating the logic if extra fields are added to superclass in the future.

    Read the article

  • Spring and hibernate.cfg.xml

    - by Steve Kuo
    How do I get Spring to load Hibernate's properties from hibernate.cfg.xml? We're using Spring and JPA (with Hibernate as the implementation). Spring's applicationContext.xml specifies the JPA dialect and Hibernate properties: <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="jpaDialect"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /> </property> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop> </props> </property> </bean> In this configuration, Spring is reading all the Hibernate properties via applicationContext.xml . When I create a hibernate.cfg.xml (located at the root of my classpath, the same level as META-INF), Hibernate doesn't read it at all (it's completely ignored). What I'm trying to do is configure Hibernate second level cache by inserting the cache properties in hibernate.cfg.xml: <cache usage="transactional|read-write|nonstrict-read-write|read-only" region="RegionName" include="all|non-lazy" />

    Read the article

  • Hibernate 3.5.0 causes extreme performance problems

    - by user303396
    I've recently updated from hibernate 3.3.1.GA to hibernate 3.5.0 and I'm having a lot of performance issues. As a test, I added around 8000 entities to my DB (which in turn cause other entities to be saved). These entities are saved in batches of 20 so that the transactions aren't too large for performance reasons. When using hibernate 3.3.1.GA all 8000 entities get saved in about 3 minutes. When using hibernate 3.5.0 it starts out slower than with hibernate 3.3.1. But it gets slower and slower. At around 4,000 entities, it sometimes takes 5 minutes just to save a batch of 20. If I then go to a mysql console and manually type in an insert statement from the mysql general query log, half of them run perfect in 0.00 seconds. And half of them take a long time (maybe 40 seconds) or timeout with "ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction" from MySQL. Has something changed in hibernate's transaction management in version 3.5.0 that I should be aware of? The ONLY thing I changed to experience these unusable performance issues is replace the following hibernate 3.3.1.GA jar files: com.springsource.org.hibernate-3.3.1.GA.jar, com.springsource.org.hibernate.annotations-3.4.0.GA.jar, com.springsource.org.hibernate.annotations.common-3.3.0.ga.jar, com.springsource.javassist-3.3.0.ga.jar with the new hibernate 3.5.0 release hibernate3.jar and javassist-3.9.0.GA.jar. Thanks.

    Read the article

  • How to setup an hibernate project using annotations compliant with JPA2.0

    - by phmr
    I would like to setup an hibernate project, for this I use the lastest hibernate 3.5-Final. BTW my IDE is Netbeans. The problem is that each time a run the application, it seems to start from a fresh database whatever db backend I use (I tried hsqldb & sqlite): here is my persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="PMMPU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>model.Extrait</class> <class>model.Mot</class> <class>model.Prefixe</class> <class>model.Suffixe</class> <class>model.Texte</class> <properties> <property name="hibernate.dialect" value="dialect.SQLiteDialect"/> <property name="hibernate.connection.username" value=""/> <property name="hibernate.connection.driver_class" value="org.sqlite.JDBC"/> <property name="hibernate.connection.password" value=""/> <property name="hibernate.connection.url" value="jdbc:sqlite:test.db"/> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence> I tried to change hibernate.hbm2ddl.auto value. I got a HibernateUtil class which takes care of creating the emf & em: public class HibernateUtil { private static EntityManagerFactory emf = null; private static EntityManager em = null; public static EntityManagerFactory getEmf() { if(emf == null) emf = Persistence.createEntityManagerFactory("PMMPU"); return emf; } public static EntityManager getEm() { if(em == null) em = getEmf().createEntityManager(); return em; } What did a I do wrong ? edit1: further research with mysql lead me to think that the problem is related to sqlite & hsqldb interaction with hibernate 3.5

    Read the article

  • hibernate criteria list problem [migrated]

    - by user1022676
    I have a user dao @Entity @Table(name="EBIGUSERTIM") public class EbigUser { private String id; private Integer source; private String entryscheme; private String fullName; private String email; private Long flags; private String status; private String createdBy; private Date createdStamp; private String modifiedBy; private Date modifiedStamp; @Id @Column(name="ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Id @Column(name="SOURCE") public Integer getSource() { return source; } public void setSource(Integer source) { this.source = source; } @Column(name="ENTRYSCHEME") public String getEntryscheme() { return entryscheme; } public void setEntryscheme(String entryscheme) { this.entryscheme = entryscheme; } @Column(name="FULLNAME") public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Column(name="EMAIL") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name="FLAGS") public Long getFlags() { return flags; } public void setFlags(Long flags) { this.flags = flags; } @Column(name="STATUS") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Column(name="CREATEDBY") public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Column(name="CREATEDSTAMP") public Date getCreatedStamp() { return createdStamp; } public void setCreatedStamp(Date createdStamp) { this.createdStamp = createdStamp; } @Column(name="MODIFIEDBY") public String getModifiedBy() { return modifiedBy; } public void setModifiedBy(String modifiedBy) { this.modifiedBy = modifiedBy; } @Column(name="MODIFIEDSTAMP") public Date getModifiedStamp() { return modifiedStamp; } public void setModifiedStamp(Date modifiedStamp) { this.modifiedStamp = modifiedStamp; } i am selecting 2 rows out of the db. The sql works select * from ebigusertim where id='blah'. It returns 2 distinct rows. When i query the data using hibernate, it appears that the object memory is not being allocated for each entry in the list. Thus, i get 2 entries in the list with the same object. Criteria userCriteria = session.createCriteria(EbigUser.class); userCriteria.add(Restrictions.eq("id", id)); userlist = userCriteria.list();

    Read the article

  • JPA/Hibernate Embedded id and fields

    - by RoD
    I would like to do something like that: An object ReportingFile that can be a LogRequest or a LogReport file. ( both got the same structure) An object Reporting containing for one logRequest, a list of logReport with a date. An example (not working) would be: @Entity @AssociationOverride( name="logRequest.fileName", joinColumns = { @JoinColumn(name="log_request_file_name") } ) public class Reporting { @EmbeddedId private ReportingFile logRequest; @CollectionOfElements(fetch = FetchType.EAGER) @JoinTable(name = "t_reports", schema="", joinColumns = {@JoinColumn(name = "log_report")}) @Fetch(FetchMode.SELECT) private List<ReportingFile> reports; @Column(name="generated_date",nullable=true) private Date generatedDate; [...] } @Embeddable public class ReportingFile { @Column(name="file_name",length=255) private String fileName; @Column(name="xml_content") private Clob xmlContent; [...] } In this sample, i have a the following error: 15.03.2010 16:37:59 [ERROR] org.springframework.web.context.ContextLoader Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [config/persistenceContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:881) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:597) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:366) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:578) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:308) at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:270) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:122) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:78) at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70) at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:97) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1325) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) ... 29 more Caused by: javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265) at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) at org.springframework.orm.jpa.LocalEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalEntityManagerFactoryBean.java:91) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:291) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334) ... 46 more Caused by: org.hibernate.AnnotationException: A Foreign key refering Reporting from Reporting has the wrong number of column. should be 2 at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:272) at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1319) at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1158) at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:600) at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:541) at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1140) at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:319) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1125) at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226) at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:159) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253) ... 52 more

    Read the article

  • Missing files when Windows 7 returns from hibernate w/ dual boot

    - by Arthur N
    I have a dual-boot setup with Ubuntu (lucid) and Windows 7. I have the Windows file system shared on Ubuntu through Samba. Occasionally, I am working on Windows and my machine will go into hibernate (i.e. when the battery level is critical). By default, my GRUB settings boot me into Ubuntu. So when I get back to my PC, sometimes I just hop into Ubuntu instead of going back to Windows. However, if I write any files to the Windows file system during that Ubuntu session, the next time I do go back to Windows (which resumes from hibernate), those files are missing. Obviously, the state of the actual file system and the hibernate snapshot become out of sync, and Windows chooses the hibernate snapshot, overriding any changes I may have made thru Ubuntu. For now, I've disabled the hibernate option in the Windows power settings, but is there any utility I can use to get back some of those missing files?

    Read the article

  • Missing files when Windows 7 returns from hibernate w/ dual boot

    - by Arthur N
    I have a dual-boot setup with Ubuntu (lucid) and Windows 7. I have the Windows file system shared on Ubuntu through Samba. Occasionally, I am working on Windows and my machine will go into hibernate (i.e. when the battery level is critical). By default, my GRUB settings boot me into Ubuntu. So when I get back to my PC, sometimes I just hop into Ubuntu instead of going back to Windows. However, if I write any files to the Windows file system during that Ubuntu session, the next time I do go back to Windows (which resumes from hibernate), those files are missing. Obviously, the state of the actual file system and the hibernate snapshot become out of sync, and Windows chooses the hibernate snapshot, overriding any changes I may have made thru Ubuntu. For now, I've disabled the hibernate option in the Windows power settings, but is there any utility I can use to get back some of those missing files?

    Read the article

  • [Hibernate Mapping] relationship set between table and mapping table to use joins.

    - by Matthew De'Loughry
    Hi guys, I have two table a "Module" table and a "StaffModule" I'm wanting to display a list of modules by which staff are present on the staffmodule mapping table. I've tried from Module join Staffmodule sm with ID = sm.MID with no luck, I get the following error Path Expected for join! however I thought I had the correct join too allow this but obviously not can any one help StaffModule HBM <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Apr 26, 2010 9:50:23 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Hibernate.Staffmodule" schema="WALK" table="STAFFMODULE"> <composite-id class="Hibernate.StaffmoduleId" name="id"> <key-many-to-one name="mid" class="Hibernate.Module"> <column name="MID"/> </key-many-to-one> <key-property name="staffid" type="int"> <column name="STAFFID"/> </key-property> </composite-id> </class> </hibernate-mapping> and Module.HBM <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Apr 26, 2010 9:50:23 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Hibernate.Module" schema="WALK" table="MODULE"> <id name="id" type="int"> <column name="ID"/> <generator class="assigned"/> </id> <property name="modulename" type="string"> <column length="50" name="MODULENAME"/> </property> <property name="teacherid" type="int"> <column name="TEACHERID" not-null="true"/> </property> </class> hope thats enough information! and thanks in advance.

    Read the article

  • Why does 12.04 try but fail to hibernate, even after I enabled hibernation?

    - by Roger Davis
    Regarding the below (-----) info from another post, my system will try (as is said below) to hibernate, but it won't get all the way there. Hard drive activity stops, but it does not shut down. If I turn the power off, then back on, it will start, but I have to "restore previous session" in the browser and other open apps don't restart, with the accompanying hassle. So because it tries, will the suggested fix then cause it to work correctly, or is the literal "try" not really what he means?!? PLEASE NOTE - this is a desktop system, not a laptop. Before enabling hibernation, please try to test whether it works correctly by running pm-hibernate in a terminal. The system will try to hibernate. If you are able to start the system again then you are more or less safe to add an override. To do so, start editing sudo nano /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla Fill it with this [Re-enable hibernate by default] Identity=unix-user:* Action=org.freedesktop.upower.hibernate ResultActive=yes Save by pressing Ctrl-O and exit nano by pressing Ctrl-X Restart and hibernation is back!

    Read the article

  • Hibernate: OutOfMemoryError persisting Blob when printing log message

    - by paul
    I have a Hibernate Entity: @Entity class Foo { //... @Lob public byte[] getBytes() { return bytes; } //.... } My VM is configured with a maximum heap size of 512 MB. When I try to persist an object which has a 75 MB large object, I get an OutOfMemoryError. The names of the methods in the stack trace (StringBuilder, ByteArrayBlobType.toLoggableString, pretty.Printer.toString) suggest that hibernate is trying to write a very large log message that contains my object. Am I correct about why hibernate is using so much memory? What is the simplest way to work around this problem? java.lang.OutOfMemoryError: Java heap space at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:44) at java.lang.StringBuilder.<init>(StringBuilder.java:81) at org.hibernate.type.ByteArrayBlobType.toString(ByteArrayBlobType.java:117) at org.hibernate.type.ByteArrayBlobType.toLoggableString(ByteArrayBlobType.java:127) at org.hibernate.pretty.Printer.toString(Printer.java:53) at org.hibernate.pretty.Printer.toString(Printer.java:90) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:97) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.jboss.seam.persistence.HibernateSessionProxy.flush(HibernateSessionProxy.java:181)

    Read the article

  • hibernate sybase db power function

    - by Vipin Thomas
    We are trying to use sybase function power to do mathematical calculation for one of the DB columns. The hibernate is generating power function as pow(?, xyzo0_.AmtScale) whereas sybase supports power function as Syntax POWER( numeric-expression-1, numeric-expression-2 ) We have tried modifying the hibernate.dialect. Have tried org.hibernate.dialect.SybaseASE15Dialect org.hibernate.dialect.Sybase11Dialect org.hibernate.dialect.SybaseAnywhereDialect but all dialects generate the power function as pow(?, xyzo0_.AmtScale). Is this hibernate issue or are we missing something?

    Read the article

  • Importing hibernate configuration file into Spring applicationContext

    - by Himanshu Yadav
    I am trying to integrate Hibernate 3 with Spring 3.1.0. The problem is that application is not able to find mapping file which declared in hibernate.cfg.xml file. Initially hibernate configuration has datasource configuration, hibernate properties and mapping hbm.xml files. Master hibernate.cfg.xml file exist in src folder. this is how Master file looks: <hibernate-configuration> <session-factory> <!-- Mappings --> <mapping resource="com/test/class1.hbm.xml"/> <mapping resource="/class2.hbm.xml"/> <mapping resource="com/test/class3.hbm.xml"/> <mapping resource="com/test/class4.hbm.xml"/> <mapping resource="com/test/class5.hbm.xml"/> Spring config is: <bean id="sessionFactoryEditSolution" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="data1"/> <property name="mappingResources"> <list> <value>/master.hibernate.cfg.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> </props> </property> </bean>

    Read the article

  • It is possible to hibernate an LXC container?

    - by Jo-Erlend Schinstad
    I know about lxc-freeze and lxc-unfreeze, but as I understand it, these simply pauses the container, similar to sending SIGSTOP and SIGCONT to a process. If I reboot the host, then the containers will cease to exist, right? I would really like a way to save state to persistent storage so that I could resume them at some later time, even the host is rebooted or something like that. I can achieve exactly what I want using VirtualBox by using the "Save machine state" mechanism, but if I could do it with LXC, it would be completely awesome.

    Read the article

  • Disable suspend / hibernate via the policykit

    - by redonath
    I am trying to run Lubuntu 12.04, but if the computer suspends I am unable to bootup again. Instead I see the bios post, the hard disk light flickers once and I have to install again (I have tried to re-install grub2). I am new to Linux and what I found that best answered my question was posted by James Henstridge. The instructions say to create disable-shutdown.pkla in etc/polkit-1/50-local.d/ but this directory does not exist, so do I create a folder titled 50-local.d in poolkit-1 or do I have to place this file elsewhere?

    Read the article

  • Second monitor not coming back on after going into hibernate

    - by dabraude
    10 and a new problem has come up. When I my machine hibernates the second monitor does not come back on. I did not have this problem in 11.04. The main monitor is plugged into a vga port, and the second plugged into a display port then an adapter to vga the system is a Dell Optiplex 790 and the graphics card is (according to lspci) a VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09) I am running the classic Gnome desktop though the problem occurs in Unity as well.

    Read the article

  • java.sql.SQLWarning: [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to X

    - by adisembiring
    Hi all, I'm using Hibernate 3.2.1 and database SQLServer2000 while I'm try to insert some data using my dao, some warning occurred like this: java.sql.SQLWarning: [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to BTN_SPP_DB at com.microsoft.jdbc.base.BaseWarnings.createSQLWarning(Unknown Source) at com.microsoft.jdbc.base.BaseWarnings.get(Unknown Source) at com.microsoft.jdbc.base.BaseConnection.getWarnings(Unknown Source) at org.hibernate.util.JDBCExceptionReporter.logAndClearWarnings(JDBCExceptionReporter.java:22) at org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:443) at org.hibernate.jdbc.ConnectionManager.aggressiveRelease(ConnectionManager.java:400) at org.hibernate.jdbc.ConnectionManager.afterTransaction(ConnectionManager.java:287) at org.hibernate.jdbc.JDBCContext.afterTransactionCompletion(JDBCContext.java:221) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:119) at co.id.hanoman.btnmw.spp.dao.TagihanDao.save(TagihanDao.java:43) at co.id.hanoman.btnmw.spp.dao.TagihanDao.save(TagihanDao.java:1) at co.id.hanoman.btnmw.spp.dao.test.TagihanDaoTest.testSave(TagihanDaoTest.java:81) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99) at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75) at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45) at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66) at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35) at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) my hibernate initialization log is: 2010-04-26 22:54:05,203 INFO [Version] Hibernate Annotations 3.3.0.GA 2010-04-26 22:54:05,234 INFO [Environment] Hibernate 3.2.1 2010-04-26 22:54:05,234 INFO [Environment] hibernate.properties not found 2010-04-26 22:54:05,234 INFO [Environment] Bytecode provider name : cglib 2010-04-26 22:54:05,234 INFO [Environment] using JDK 1.4 java.sql.Timestamp handling 2010-04-26 22:54:05,343 INFO [Configuration] configuring from resource: /hibernate.cfg.xml 2010-04-26 22:54:05,343 INFO [Configuration] Configuration resource: /hibernate.cfg.xml 2010-04-26 22:54:05,406 DEBUG [DTDEntityResolver] trying to resolve system-id [http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd] 2010-04-26 22:54:05,406 DEBUG [DTDEntityResolver] recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/ 2010-04-26 22:54:05,406 DEBUG [DTDEntityResolver] located [http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd] in classpath 2010-04-26 22:54:05,453 DEBUG [Configuration] hibernate.dialect=org.hibernate.dialect.SQLServerDialect 2010-04-26 22:54:05,453 DEBUG [Configuration] hibernate.connection.driver_class=com.microsoft.jdbc.sqlserver.SQLServerDriver 2010-04-26 22:54:05,453 DEBUG [Configuration] hibernate.connection.url=jdbc:microsoft:sqlserver://12.56.11.65:1433;databaseName=BTN_SPP_DB 2010-04-26 22:54:05,453 DEBUG [Configuration] hibernate.connection.username=spp 2010-04-26 22:54:05,453 DEBUG [Configuration] hibernate.connection.password=spp

    Read the article

  • Hibernate/Spring: failed to lazily initialize - no session or session was closed

    - by Niko
    I know something similar has been asked already, but unfortunately I wasn't able to find a reliable answer - even with searching for over 2 days. The basic problem is the same as asked multiple time. I have a simple program with two POJOs Event and User - where a user can have multiple events. @Entity @Table public class Event { private Long id; private String name; private User user; @Column @Id @GeneratedValue public Long getId() {return id;} public void setId(Long id) { this.id = id; } @Column public String getName() {return name;} public void setName(String name) {this.name = name;} @ManyToOne @JoinColumn(name="user_id") public User getUser() {return user;} public void setUser(User user) {this.user = user;} } @Entity @Table public class User { private Long id; private String name; private List events; @Column @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy="user", fetch=FetchType.LAZY) public List getEvents() { return events; } public void setEvents(List events) { this.events = events; } } Note: This is a sample project. I really want to use Lazy fetching here. I use spring and hibernate and have a simple basic-db.xml for loading: <?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="thread" <property name="driverClassName" value="com.mysql.jdbc.Driver" / <property name="url" value="jdbc:mysql://192.168.1.34:3306/hibernateTest" / <property name="username" value="root" / <property name="password" value="" / <aop:scoped-proxy/ </bean <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer" <property name="scopes" <map <entry key="thread" <bean class="org.springframework.context.support.SimpleThreadScope" / </entry </map </property </bean <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" scope="thread" <property name="dataSource" ref="myDataSource" / <property name="annotatedClasses" <list <valuedata.model.User</value <valuedata.model.Event</value </list </property <property name="hibernateProperties" <props <prop key="hibernate.dialect"org.hibernate.dialect.MySQLDialect</prop <prop key="hibernate.show_sql"true</prop <prop key="hibernate.hbm2ddl.auto"create</prop </props </property <aop:scoped-proxy/ </bean <bean id="myUserDAO" class="data.dao.impl.UserDaoImpl" <property name="sessionFactory" ref="mySessionFactory" / </bean <bean id="myEventDAO" class="data.dao.impl.EventDaoImpl" <property name="sessionFactory" ref="mySessionFactory" / </bean </beans Note: I played around with the CustomScopeConfigurer and SimpleThreadScope, but that didnt change anything. I have a simple dao-impl (only pasting the userDao - the EventDao is pretty much the same - except with out the "listWith" function: public class UserDaoImpl implements UserDao{ private HibernateTemplate hibernateTemplate; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } @SuppressWarnings("unchecked") @Override public List listUser() { return hibernateTemplate.find("from User"); } @Override public void saveUser(User user) { hibernateTemplate.saveOrUpdate(user); } @Override public List listUserWithEvent() { List users = hibernateTemplate.find("from User"); for (User user : users) { System.out.println("LIST : " + user.getName() + ":"); user.getEvents().size(); } return users; } } I am getting the org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed at the line with user.getEvents().size(); And last but not least here is the Test class I use: public class HibernateTest { public static void main(String[] args) { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("basic-db.xml"); UserDao udao = (UserDao) ac.getBean("myUserDAO"); EventDao edao = (EventDao) ac.getBean("myEventDAO"); System.out.println("New user..."); User user = new User(); user.setName("test"); Event event1 = new Event(); event1.setName("Birthday1"); event1.setUser(user); Event event2 = new Event(); event2.setName("Birthday2"); event2.setUser(user); udao.saveUser(user); edao.saveEvent(event1); edao.saveEvent(event2); List users = udao.listUserWithEvent(); System.out.println("Events for users"); for (User u : users) { System.out.println(u.getId() + ":" + u.getName() + " --"); for (Event e : u.getEvents()) { System.out.println("\t" + e.getId() + ":" + e.getName()); } } ((ConfigurableApplicationContext)ac).close(); } } and here is the Exception I get: 1621 [main] ERROR org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at data.dao.impl.UserDaoImpl.listUserWithEvent(UserDaoImpl.java:38) at HibernateTest.main(HibernateTest.java:44) Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: data.model.User.events, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at data.dao.impl.UserDaoImpl.listUserWithEvent(UserDaoImpl.java:38) at HibernateTest.main(HibernateTest.java:44) Things I tried but did not work: assign a threadScope and using beanfactory (I used "request" or "thread" - no difference noticed): // scope stuff Scope threadScope = new SimpleThreadScope(); ConfigurableListableBeanFactory beanFactory = ac.getBeanFactory(); beanFactory.registerScope("request", threadScope); ac.refresh(); ... Setting up a transaction by getting the session object from the deo: ... Transaction tx = ((UserDaoImpl)udao).getSession().beginTransaction(); tx.begin(); users = udao.listUserWithEvent(); ... getting a transaction within the listUserWithEvent() public List listUserWithEvent() { SessionFactory sf = hibernateTemplate.getSessionFactory(); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); tx.begin(); List users = hibernateTemplate.find("from User"); for (User user : users) { System.out.println("LIST : " + user.getName() + ":"); user.getEvents().size(); } tx.commit(); return users; } I am really out of ideas by now. Also, using the listUser or listEvent just work fine.

    Read the article

  • Atomikos with Hibernate will exhaust db connections

    - by peter
    I am testing an application (Spring 2.5, Hibernate 3.5.0 Beta, Atomikos 3.6.2, and Postgreql 8.4.2) with the configuration for the DAO listed below. The problem that I see is that the pool of 10 connections with the dataSource gets exhausted after the 10's transaction. I know 'hibernate.connection.release_mode' has no effect unless the session is obtained with openSession rather then using a contextual session. I am wandering if anyone has found a way to instruct atomikos code to release connections after any transaction. Thank you Peter <bean id="dataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close"> <property name="uniqueResourceName"><value>XADBMS</value></property> <property name="xaDataSourceClassName"> <value>org.postgresql.xa.PGXADataSource</value> </property> <property name="xaProperties"> <props> <prop key="databaseName">${jdbc.name}</prop> <prop key="serverName">${jdbc.server}</prop> <prop key="portNumber">${jdbc.port}</prop> <prop key="user">${jdbc.username}</prop> <prop key="password">${jdbc.password}</prop> </props> </property> <property name="poolSize"><value>10</value></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="mappingResources"> <list> <value>Abc.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">on</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.connection.isolation">3</prop> <prop key="hibernate.current_session_context_class">jta</prop> <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop> <prop key="hibernate.transaction.manager_lookup_class">com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup</prop> <prop key="hibernate.connection.release_mode">auto</prop> <prop key="hibernate.current_session_context_class">org.hibernate.context.JTASessionContext</prop> <prop key="hibernate.transaction.auto_close_session">true</prop> </props> </property> </bean> <!-- Transaction definition here --> <bean id="userTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp" init-method="init" destroy-method="shutdownForce"> <constructor-arg> <props> <prop key="com.atomikos.icatch.service"> com.atomikos.icatch.standalone.UserTransactionServiceFactory </prop> </props> </constructor-arg> </bean> <!-- Construct Atomikos UserTransactionManager, needed to configure Spring --> <bean id="AtomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close" depends-on="userTransactionService"> <property name="forceShutdown" value="false" /> </bean> <!-- Also use Atomikos UserTransactionImp, needed to configure Spring --> <bean id="AtomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp" depends-on="userTransactionService"> <property name="transactionTimeout" value="300" /> </bean> <!-- Configure the Spring framework to use JTA transactions from Atomikos --> <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" depends-on="userTransactionService"> <property name="transactionManager" ref="AtomikosTransactionManager" /> <property name="userTransaction" ref="AtomikosUserTransaction" /> </bean> <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true" propagation="REQUIRED"/> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:advisor pointcut="execution(* *.*.AbcDao.*(..))" advice-ref="txAdvice"/> </aop:config> <!-- DAO objects --> <bean id="abcDao" class="test.dao.impl.HibernateAbcDao" scope="singleton"> <property name="sessionFactory" ref="sessionFactory"/> </bean>

    Read the article

  • Save blob to DB using hibernate

    - by Link123
    Hey! I tried save file to MySQL using blob with hibernate3. But I always have java.lang.UnsupportedOperationException: Blob may not be manipulated from creating session org.hibernate.lob.BlobImpl.excep(BlobImpl.java:127) Here some code. package com.uni.domain; public class File extends Identifier { private byte[] data; private String contentType; public byte[] getData() { return data; } public File() {} public void setData(byte[] photo) { this.data = photo; } public boolean isNew() { return true; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } } package com.uni.domain; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.usertype.UserType; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.sql.*; import java.util.Arrays; public class PhotoType implements UserType { public int[] sqlTypes() { return new int[]{Types.BLOB}; } public Class returnedClass() { return byte[].class; } public boolean equals(Object o, Object o1) throws HibernateException { return Arrays.equals((byte[]) o, (byte[]) o1); } public int hashCode(Object o) throws HibernateException { return o.hashCode(); } public Object nullSafeGet(ResultSet resultSet, String[] strings, Object o) throws HibernateException, SQLException { Blob blob = resultSet.getBlob(strings[0]); return blob.getBytes(1, (int) blob.length()); } public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { st.setBlob(index, Hibernate.createBlob((byte[]) value)); } public Object deepCopy(Object value) { if (value == null) return null; byte[] bytes = (byte[]) value; byte[] result = new byte[bytes.length]; System.arraycopy(bytes, 0, result, 0, bytes.length); return result; } public boolean isMutable() { return true; } public Serializable disassemble(Object o) throws HibernateException { return null; . } public Object assemble(Serializable serializable, Object o) throws HibernateException { return null; . } public Object replace(Object o, Object o1, Object o2) throws HibernateException { return null; . } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.uni.domain"> <class name="com.uni.domain.File"> <id name="id"> <generator class="native"/> </id> <property name="data" type="com.uni.domain.FleType"/> <property name="contentType"/> </class> </hibernate-mapping> Help me please. Where I’m wrong?

    Read the article

  • Disable Autocommit with Spring/Hibernate/C3P0/Atomikos ?

    - by HDave
    I have a JPA/Hibernate application and am trying to get it to run against H2 and MySQL. Currently I am using Atomikos for transactions and C3P0 for connection pooling. Despite my best efforts I am still seeing this in the log file (and DAO integration tests are failing with org.hibernate.NonUniqueObjectException even though Spring Test should be rolling back the database after each test method): [20100613 23:06:34] DEBUG [main] SessionFactoryImpl.(242) | instantiating session factory with properties: .....edited for brevity.... hibernate.connection.autocommit=true, ....more stuff follows The connection URL to H2 has AUTOCOMMIT=OFF, but according to the H2 documentation: this will not work as expected when using a connection pool (the connection pool manager will re-enable autocommit when returning the connection to the pool, so autocommit will only be disabled the first time the connection is used So I figured (apparently correctly) that Hibernate is where I'll have to indicate I want autocommit off. I found the autocommit property documented here and I put it in my EntityManagerFactory config as follows: <bean id="myappTestLocalEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="myapp-core" /> <property name="persistenceUnitPostProcessors"> <bean class="com.myapp.core.persist.util.JtaPersistenceUnitPostProcessor"> <property name="jtaDataSource" ref="myappPersistTestJdbcDataSource" /> </bean> </property> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="database" value="$DS{hibernate.database}" /> <property name="databasePlatform" value="$DS{hibernate.dialect}" /> </bean> </property> <property name="jpaProperties"> <props> <prop key="hibernate.transaction.factory_class">com.atomikos.icatch.jta.hibernate3.AtomikosJTATransactionFactory</prop> <prop key="hibernate.transaction.manager_lookup_class">com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup</prop> <prop key="hibernate.connection.autocommit">false</prop> <prop key="hibernate.format_sql">true"</prop> <prop key="hibernate.use_sql_comments">true</prop> </property> </bean>

    Read the article

  • How can I resolve Hibernate 3's ConstraintViolationException when updating a Persistent Entity's Col

    - by Tim Visher
    I'm trying to discover why two nearly identical class sets are behaving different from Hibernate 3's perspective. I'm fairly new to Hibernate in general and I'm hoping I'm missing something fairly obvious about the mappings or timing issues or something along those lines but I spent the whole day yesterday staring at the two sets and any differences that would lead to one being able to be persisted and the other not completely escaped me. I appologize in advance for the length of this question but it all hinges around some pretty specific implementation details. I have the following class mapped with Annotations and managed by Hibernate 3.? (if the specific specific version turns out to be pertinent, I'll figure out what it is). Java version is 1.6. ... @Embeddable public class JobStateChange implements Comparable<JobStateChange> { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date date; @Enumerated(EnumType.STRING) @Column(nullable = false, length = JobState.FIELD_LENGTH) private JobState state; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "acting_user_id", nullable = false) private User actingUser; public JobStateChange() { } @Override public int compareTo(final JobStateChange o) { return this.date.compareTo(o.date); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } else if (!(obj instanceof JobStateChange)) { return false; } JobStateChange candidate = (JobStateChange) obj; return this.state == candidate.state && this.actingUser.equals(candidate.getUser()) && this.date.equals(candidate.getDate()); } @Override public int hashCode() { return this.state.hashCode() + this.actingUser.hashCode() + this.date.hashCode(); } } It is mapped as a Hibernate CollectionOfElements in the class Job as follows: ... @Entity @Table( name = "job", uniqueConstraints = { @UniqueConstraint( columnNames = { "agency", //Job Name "payment_type", //Job Name "payment_file", //Job Name "date_of_payment", "payment_control_number", "truck_number" }) }) public class Job implements Serializable { private static final long serialVersionUID = -1131729422634638834L; ... @org.hibernate.annotations.CollectionOfElements @JoinTable(name = "job_state", joinColumns = @JoinColumn(name = "job_id")) @Sort(type = SortType.NATURAL) private final SortedSet<JobStateChange> stateChanges = new TreeSet<JobStateChange>(); ... public void advanceState( final User actor, final Date date) { JobState nextState; LOGGER.debug("Current state of {} is {}.", this, this.getCurrentState()); if (null == this.currentState) { nextState = JobState.BEGINNING; } else { if (!this.isAdvanceable()) { throw new IllegalAdvancementException(this.currentState.illegalAdvancementStateMessage); } if (this.currentState.isDivergent()) { nextState = this.currentState.getNextState(this); } else { nextState = this.currentState.getNextState(); } } JobStateChange stateChange = new JobStateChange(nextState, actor, date); this.setCurrentState(stateChange.getState()); this.stateChanges.add(stateChange); LOGGER.debug("Advanced {} to {}", this, this.getCurrentState()); } private void setCurrentState(final JobState jobState) { this.currentState = jobState; } boolean isAdvanceable() { return this.getCurrentState().isAdvanceable(this); } ... @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Job)) { return false; } Job otherJob = (Job) obj; return this.getName().equals(otherJob.getName()) && this.getDateOfPayment().equals(otherJob.getDateOfPayment()) && this.getPaymentControlNumber().equals(otherJob.getPaymentControlNumber()) && this.getTruckNumber().equals(otherJob.getTruckNumber()); } @Override public int hashCode() { return this.getName().hashCode() + this.getDateOfPayment().hashCode() + this.getPaymentControlNumber().hashCode() + this.getTruckNumber().hashCode(); } ... } The purpose of JobStateChange is to record when the Job moves through a series of State Changes that are outline in JobState as enums which know about advancement and decrement rules. The interface used to advance Jobs through a series of states is to call Job.advanceState() with a Date and a User. If the Job is advanceable according to rules coded in the enum, then a new StateChange is added to the SortedSet and everyone's happy. If not, an IllegalAdvancementException is thrown. The DDL this generates is as follows: ... drop table job; drop table job_state; ... create table job ( id bigint generated by default as identity, current_state varchar(25), date_of_payment date not null, beginningCheckNumber varchar(8) not null, item_count integer, agency varchar(10) not null, payment_file varchar(25) not null, payment_type varchar(25) not null, endingCheckNumber varchar(8) not null, payment_control_number varchar(4) not null, truck_number varchar(255) not null, wrapping_system_type varchar(15) not null, printer_id bigint, primary key (id), unique (agency, payment_type, payment_file, date_of_payment, payment_control_number, truck_number) ); create table job_state ( job_id bigint not null, acting_user_id bigint not null, date timestamp not null, state varchar(25) not null, primary key (job_id, acting_user_id, date, state) ); ... alter table job add constraint FK19BBD12FB9D70 foreign key (printer_id) references printer; alter table job_state add constraint FK57C2418FED1F0D21 foreign key (acting_user_id) references app_user; alter table job_state add constraint FK57C2418FABE090B3 foreign key (job_id) references job; ... The database is seeded with the following data prior to running tests ... insert into job (id, agency, payment_type, payment_file, payment_control_number, date_of_payment, beginningCheckNumber, endingCheckNumber, item_count, current_state, printer_id, wrapping_system_type, truck_number) values (-3, 'RRB', 'Monthly', 'Monthly','4501','1998-12-01 08:31:16' , '00000001','00040000', 40000, 'UNASSIGNED', null, 'KERN', '02'); insert into job_state (job_id, acting_user_id, date, state) values (-3, -1, '1998-11-30 08:31:17', 'UNASSIGNED'); ... After the database schema is automatically generated and rebuilt by the Hibernate tool. The following test runs fine up until the call to Session.flush() ... @ContextConfiguration(locations = { "/applicationContext-data.xml", "/applicationContext-service.xml" }) public class JobDaoIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private JobDao jobDao; @Autowired private SessionFactory sessionFactory; @Autowired private UserService userService; @Autowired private PrinterService printerService; ... @Test public void saveJob_JobAdvancedToAssigned_AllExpectedStateChanges() { //Get an unassigned Job Job job = this.jobDao.getJob(-3L); assertEquals(JobState.UNASSIGNED, job.getCurrentState()); Date advancedToUnassigned = new GregorianCalendar(1998, 10, 30, 8, 31, 17).getTime(); assertEquals(advancedToUnassigned, job.getStateChange(JobState.UNASSIGNED).getDate()); //Satisfy advancement constraints and advance job.setPrinter(this.printerService.getPrinter(-1L)); Date advancedToAssigned = new Date(); job.advanceState( this.userService.getUserByUsername("admin"), advancedToAssigned); assertEquals(JobState.ASSIGNED, job.getCurrentState()); assertEquals(advancedToUnassigned, job.getStateChange(JobState.UNASSIGNED).getDate()); assertEquals(advancedToAssigned, job.getStateChange(JobState.ASSIGNED).getDate()); //Persist to DB this.sessionFactory.getCurrentSession().flush(); ... } ... } The error thrown is SQLCODE=-803, SQLSTATE=23505: could not insert collection rows: [jaci.model.job.Job.stateChanges#-3] org.hibernate.exception.ConstraintViolationException: could not insert collection rows: [jaci.model.job.Job.stateChanges#-3] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1416) at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:86) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:170) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at jaci.dao.JobDaoIntegrationTest.saveJob_JobAdvancedToAssigned_AllExpectedStateChanges(JobDaoIntegrationTest.java:98) at org.springframework.test.context.junit4.SpringTestMethod.invoke(SpringTestMethod.java:160) at org.springframework.test.context.junit4.SpringMethodRoadie.runTestMethod(SpringMethodRoadie.java:233) at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:333) at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217) at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197) at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97) Caused by: com.ibm.db2.jcc.b.lm: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=1;ACI_APP.JOB_STATE, DRIVER=3.50.152 at com.ibm.db2.jcc.b.wc.a(wc.java:575) at com.ibm.db2.jcc.b.wc.a(wc.java:57) at com.ibm.db2.jcc.b.wc.a(wc.java:126) at com.ibm.db2.jcc.b.tk.b(tk.java:1593) at com.ibm.db2.jcc.b.tk.c(tk.java:1576) at com.ibm.db2.jcc.t4.db.k(db.java:353) at com.ibm.db2.jcc.t4.db.a(db.java:59) at com.ibm.db2.jcc.t4.t.a(t.java:50) at com.ibm.db2.jcc.t4.tb.b(tb.java:200) at com.ibm.db2.jcc.b.uk.Gb(uk.java:2355) at com.ibm.db2.jcc.b.uk.e(uk.java:3129) at com.ibm.db2.jcc.b.uk.zb(uk.java:568) at com.ibm.db2.jcc.b.uk.executeUpdate(uk.java:551) at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:46) at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1389) Therein lies my problem… A nearly identical Class set (in fact, so identical that I've been chomping at the bit to make it a single class that serves both business entities) runs absolutely fine. It is identical except for name. Instead of Job it's Web. Instead of JobStateChange it's WebStateChange. Instead of JobState it's WebState. Both Job and Web's SortedSet of StateChanges are mapped as a Hibernate CollectionOfElements. Both are @Embeddable. Both are SortType.Natural. Both are backed by an Enumeration with some advancement rules in it. And yet when a nearly identical test is run for Web, no issue is discovered and the data flushes fine. For the sake of brevity I won't include all of the Web classes here, but I will include the test and if anyone wants to see the actual sources, I'll include them (just leave a comment). The data seed: insert into web (id, stock_type, pallet, pallet_id, date_received, first_icn, last_icn, shipment_id, current_state) values (-1, 'PF', '0011', 'A', '2008-12-31 08:30:02', '000000001', '000080000', -1, 'UNSTAGED'); insert into web_state (web_id, date, state, acting_user_id) values (-1, '2008-12-31 08:30:03', 'UNSTAGED', -1); The test: ... @ContextConfiguration(locations = { "/applicationContext-data.xml", "/applicationContext-service.xml" }) public class WebDaoIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private WebDao webDao; @Autowired private UserService userService; @Autowired private SessionFactory sessionFactory; ... @Test public void saveWeb_WebAdvancedToNewState_AllExpectedStateChanges() { Web web = this.webDao.getWeb(-1L); Date advancedToUnstaged = new GregorianCalendar(2008, 11, 31, 8, 30, 3).getTime(); assertEquals(WebState.UNSTAGED, web.getCurrentState()); assertEquals(advancedToUnstaged, web.getState(WebState.UNSTAGED).getDate()); Date advancedToStaged = new Date(); web.advanceState( this.userService.getUserByUsername("admin"), advancedToStaged); this.sessionFactory.getCurrentSession().flush(); web = this.webDao.getWeb(web.getId()); assertEquals( "Web should have moved to STAGED State.", WebState.STAGED, web.getCurrentState()); assertEquals(advancedToUnstaged, web.getState(WebState.UNSTAGED).getDate()); assertEquals(advancedToStaged, web.getState(WebState.STAGED).getDate()); assertNotNull(web.getState(WebState.UNSTAGED)); assertNotNull(web.getState(WebState.STAGED)); } ... } As you can see, I assert that the Web was reconstituted the way I expect, I advance it, flush it to the DB, and then re-get it and verify that the states are as I expect. Everything works perfectly. Not so with Job. A possibly pertinent detail: the reconstitution code works fine if I cease to map JobStateChange.data as a TIMESTAMP and instead as a DATE, and ensure that all of the StateChanges always occur on different Dates. The problem is that this particular business entity can go through many state changes in a single day and so it needs to be sorted by time stamp rather than by date. If I don't do this then I can't sort the StateChanges correctly. That being said, WebStateChange.date is also mapped as a TIMESTAMP and so I again remain absolutely befuddled as to where this error is arising from. I tried to do a fairly thorough job of giving all of the technical details of the implementation but as this particular question is very implementation specific, if I missed anything just let me know in the comments and I'll include it. Thanks so much for your help! UPDATE: Since it turns out to be important to the solution of my problem, I have to include the pertinent bits of the WebStateChange class as well. ... @Embeddable public class WebStateChange implements Comparable<WebStateChange> { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date date; @Enumerated(EnumType.STRING) @Column(nullable = false, length = WebState.FIELD_LENGTH) private WebState state; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "acting_user_id", nullable = false) private User actingUser; ... WebStateChange( final WebState state, final User actingUser, final Date date) { ExceptionUtils.illegalNullArgs(state, actingUser, date); this.state = state; this.actingUser = actingUser; this.date = new Date(date.getTime()); } @Override public int compareTo(final WebStateChange otherStateChange) { return this.date.compareTo(otherStateChange.date); } @Override public boolean equals(final Object candidate) { if (this == candidate) { return true; } else if (!(candidate instanceof WebStateChange)) { return false; } WebStateChange candidateWebState = (WebStateChange) candidate; return this.getState() == candidateWebState.getState() && this.getUser().equals(candidateWebState.getUser()) && this.getDate().equals(candidateWebState.getDate()); } @Override public int hashCode() { return this.getState().hashCode() + this.getUser().hashCode() + this.getDate().hashCode(); } ... }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >