Hibernate Books

All times are UTC - 5 hours [ DST ]



Post new topic Reply to topic  [ 8 posts ] 
Author Message
 Post subject: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Sat Nov 05, 2011 6:36 am 
Newbie

Joined: Sat Nov 05, 2011 6:10 am
Posts: 12
Hello all,
I have a problem with my webapp, it's probably a misunterstanding of Annotation and Search.
I need to insert data inside lucene/mysql outside a servlet context, using a Quartz trigger. So i have a class wich read an xml file and calling each needed manager like this :
Code:
      try{
         ApplicationContext ap = new ClassPathXmlApplicationContext("org/litis/plair/domain/dao/applicationContext*.xml");
         articleManager = (ArticleManager) ap.getBean("articleManager");
         articlepartManager= (ArticlepartManager) ap.getBean("articlepartManager");
         articlefulltextManager= (ArticlefulltextManager) ap.getBean("articlefulltextManager");   
      }
      catch(Exception e){
         log.error("cannot initiate JPA Manager !!!",e);
      }


Then, i parse an xml file and create new data using theses manager :
Code:
         Article article = new Article();

[... do xml parsing stuff and article.set ....]
         articleManager.persist(article);


When i call persist i got this exception :
Code:
;2011-11-04;17:32:35;AltoOCRImport;[ERROR];error while importing OCR Results
;org.springframework.orm.hibernate3.HibernateSystemException: Error while indexing in Hibernate Search (before transaction completion); nested exception is org.hibernate.HibernateException: Error while indexing in Hibernate Search (before transaction completion)
   at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
   at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:102)
   at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:471)
   at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
   at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
   at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
   at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
   at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
   at $Proxy149.persist(Unknown Source)
   at org.litis.plair.administration.AltoOCRImport.addXmlFile(AltoOCRImport.java:280)
   at org.litis.plair.administration.AltoOCRImport.run(AltoOCRImport.java:183)
   at org.litis.plair.service.old.ExecuteRunnerJob.execute(ExecuteRunnerJob.java:20)
   at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
   at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: org.hibernate.HibernateException: Error while indexing in Hibernate Search (before transaction completion)
   at org.hibernate.search.backend.impl.EventSourceTransactionContext$DelegateToSynchronizationOnBeforeTx.doBeforeTransactionCompletion(EventSourceTransactionContext.java:175)
   at org.hibernate.engine.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:543)
   at org.hibernate.engine.ActionQueue.beforeTransactionCompletion(ActionQueue.java:216)
   at org.hibernate.impl.SessionImpl.beforeTransactionCompletion(SessionImpl.java:571)
   at org.hibernate.jdbc.JDBCContext.beforeTransactionCompletion(JDBCContext.java:250)
   at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:138)
   at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
   at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467)
   ... 12 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
   at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
   at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
   at org.hibernate.search.util.HibernateHelper.unproxy(HibernateHelper.java:62)
   at org.hibernate.search.engine.impl.HibernateStatelessInitializer.unproxy(HibernateStatelessInitializer.java:48)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.buildDocumentFields(DocumentBuilderIndexedEntity.java:459)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.buildDocumentFields(DocumentBuilderIndexedEntity.java:552)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.buildDocumentFields(DocumentBuilderIndexedEntity.java:552)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.getDocument(DocumentBuilderIndexedEntity.java:443)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.createAddWork(DocumentBuilderIndexedEntity.java:380)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.addWorkToQueue(DocumentBuilderIndexedEntity.java:358)
   at org.hibernate.search.engine.WorkPlan$PerEntityWork.enqueueLuceneWork(WorkPlan.java:456)
   at org.hibernate.search.engine.WorkPlan$PerClassWork.enqueueLuceneWork(WorkPlan.java:257)
   at org.hibernate.search.engine.WorkPlan.getPlannedLuceneWork(WorkPlan.java:150)
   at org.hibernate.search.backend.WorkQueue.prepareWorkPlan(WorkQueue.java:134)
   at org.hibernate.search.backend.impl.BatchedQueueingProcessor.prepareWorks(BatchedQueueingProcessor.java:124)
   at org.hibernate.search.backend.impl.PostTransactionWorkQueueSynchronization.beforeCompletion(PostTransactionWorkQueueSynchronization.java:89)
   at org.hibernate.search.backend.impl.EventSourceTransactionContext$DelegateToSynchronizationOnBeforeTx.doBeforeTransactionCompletion(EventSourceTransactionContext.java:172)
   ... 19 more


I searched over the web for answer, saw that post viewtopic.php?f=9&t=1012195 talking about org.hibernate.search.FullTextSession.flushToIndexes() but i don't know how to use it, or if it will correct my issue.
Because i used annotations to describe my dao, i'm not sure of to get the current session ? Can somebody help me ?

Here is my JPA DAO implementation code :
Code:
/**
* JPA implementation of the DAO for domain model class Article.
*
* @see org.litis.plair.domain.model.Article
* @author Thomas.palfray
*/
@Repository("articleDao")
public class JpaArticleDao implements ArticleDao {

   private final Logger log = LoggerFactory.getLogger(JpaArticleDao.class);

   @PersistenceContext
   private EntityManager entityManager;

   /**
    * {@inheritDoc}
    */
   public void persist(Article transientArticle) {
      if(log.isDebugEnabled())log.debug("persisting Article instance");
      try {
         entityManager.persist(transientArticle);
         if(log.isDebugEnabled())log.debug("persist successful");
      } catch (RuntimeException re) {
         log.error("persist failed", re);
      }
   }


And my model with annotations :
Code:
package org.litis.plair.domain.model;

// Generated 17 févr. 2011 14:12:05 by Hibernate Tools 3.3.0.GA

import static javax.persistence.GenerationType.IDENTITY;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Boost;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Store;

/**
* Article generated by hbm2java
*/
@Entity
@Table(name = "article", catalog = "nla")
@Indexed(index="articleText")
@Analyzer(impl = StandardAnalyzer.class)
public class Article implements java.io.Serializable {

   private static final long serialVersionUID = 1L;

   private Integer id;
   private Page page;
   private String heading;
   private String subheading;
   private String abstract_;
   private int firstIllustrationId;
   private String category;
   private int wordcount;
   private Set<Correction> corrections = new HashSet<Correction>(0);
   private Articlefulltext articlefulltext;
   private Set<Tag> tags = new HashSet<Tag>(0);
   private Set<Annotation> annotations = new HashSet<Annotation>(0);
   private Set<Articlepart> articleparts = new HashSet<Articlepart>(0);

   public Article() {
   }

   public Article(Page page, String abstract_, int firstIllustrationId,
         String category, int wordcount) {
      this.page = page;
      this.abstract_ = abstract_;
      this.firstIllustrationId = firstIllustrationId;
      this.category = category;
      this.wordcount = wordcount;
   }

   public Article(Page page, String heading, String subheading,
         String abstract_, int firstIllustrationId, String category,
         int wordcount, Set<Correction> corrections,
         Articlefulltext articlefulltext, Set<Tag> tags,
         Set<Annotation> annotations, Set<Articlepart> articleparts) {
      this.page = page;
      this.heading = heading;
      this.subheading = subheading;
      this.abstract_ = abstract_;
      this.firstIllustrationId = firstIllustrationId;
      this.category = category;
      this.wordcount = wordcount;
      this.corrections = corrections;
      this.articlefulltext = articlefulltext;
      this.tags = tags;
      this.annotations = annotations;
      this.articleparts = articleparts;
   }

   @Id
   @GeneratedValue(strategy = IDENTITY)
   @Column(name = "id", unique = true, nullable = false)
   @DocumentId
   @Field(name="aid", store=Store.YES, index=Index.NO_NORMS)   
   public Integer getId() {
      return this.id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "firstpageid", nullable = false)
   @IndexedEmbedded
   public Page getPage() {
      return this.page;
   }

   public void setPage(Page page) {
      this.page = page;
   }

   @Column(name = "heading", length = 300)
   @Field(name= "title", index = Index.TOKENIZED, store = Store.YES)
   @Boost(2.5f)
   public String getHeading() {
      return this.heading;
   }

   public void setHeading(String heading) {
      this.heading = heading;
   }

   @Column(name = "subheading", length = 300)
   public String getSubheading() {
      return this.subheading;
   }

   public void setSubheading(String subheading) {
      this.subheading = subheading;
   }

   @Column(name = "abstract", nullable = false, length = 65535)
   public String getAbstract_() {
      return this.abstract_;
   }

   public void setAbstract_(String abstract_) {
      this.abstract_ = abstract_;
   }

   @Column(name = "firstIllustrationId", nullable = false)
   public int getFirstIllustrationId() {
      return this.firstIllustrationId;
   }

   public void setFirstIllustrationId(int firstIllustrationId) {
      this.firstIllustrationId = firstIllustrationId;
   }

   @Column(name = "category", nullable = false, length = 100)
   @Field(name= "category", index = Index.NO_NORMS, store = Store.YES)
   public String getCategory() {
      return this.category;
   }

   public void setCategory(String category) {
      this.category = category;
   }

   @Column(name = "wordcount", nullable = false)
   public int getWordcount() {
      return this.wordcount;
   }

   public void setWordcount(int wordcount) {
      this.wordcount = wordcount;
   }

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "article")
   public Set<Correction> getCorrections() {
      return this.corrections;
   }

   public void setCorrections(Set<Correction> corrections) {
      this.corrections = corrections;
   }

   @OneToOne(fetch = FetchType.LAZY, mappedBy = "article")
   @IndexedEmbedded
   public Articlefulltext getArticlefulltext() {
      return this.articlefulltext;
   }

   public void setArticlefulltext(Articlefulltext articlefulltext) {
      this.articlefulltext = articlefulltext;
   }

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "article")
   @IndexedEmbedded
   public Set<Tag> getTags() {
      return this.tags;
   }

   public void setTags(Set<Tag> tags) {
      this.tags = tags;
   }

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "article")
   public Set<Annotation> getAnnotations() {
      return this.annotations;
   }

   public void setAnnotations(Set<Annotation> annotations) {
      this.annotations = annotations;
   }

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "article")
   public Set<Articlepart> getArticleparts() {
      return this.articleparts;
   }

   public void setArticleparts(Set<Articlepart> articleparts) {
      this.articleparts = articleparts;
   }

   @Override
   public String toString(){
      String s = "[id:"+this.getId()+"]" +
               "[heading:"+this.getHeading().length()+"]" +
               "[subheading:"+this.getSubheading().length()+"]" +
               "[abstract:"+this.getAbstract_().length()+"]";
      return s;
   }
}


Thanks in advance for the help you could provide :)


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Mon Nov 07, 2011 5:44 am 
Hibernate Team
Hibernate Team

Joined: Thu Apr 05, 2007 5:52 am
Posts: 1689
Location: Sweden
Where and how is the Hibernate Session opened and closed? Looks like during the indexing of indexed embedded properties the session is closed and lazy loaded associations cannot be loaded.


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Mon Nov 07, 2011 5:55 am 
Newbie

Joined: Sat Nov 05, 2011 6:10 am
Posts: 12
This is what i don't understand. I guessed that the session is handled by the transaction Manager in my config ?
This is weird, all other request on theses beans are working ... Do i have to handle the session myself to be sure that lazyexception won't show up ? Like by using AnnotationConfiguration() ?

Code:
   <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
         <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
        </property>
      <property name="dataSource" ref="dataSource" />
      <property name="jpaDialect">
         <bean class="${jpa.dialect}" />
      </property>
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="${hibernate.show_sql}" />
            <property name="databasePlatform" value="${hibernate.dialect}" />
            <!-- On ne genere pas la BDD au demarrage -->
            <property name="generateDdl" value="false" />
         </bean>
      </property>
   </bean>

   <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="entityManagerFactory" />
   </bean>

   <!-- enable the configuration of transactional behavior based on annotations -->
   <tx:annotation-driven transaction-manager="txManager" />


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Mon Nov 07, 2011 6:26 am 
Hibernate Team
Hibernate Team

Joined: Thu Apr 05, 2007 5:52 am
Posts: 1689
Location: Sweden
Well, normally the session is handled via the so called "open session in view" pattern or you use Conversations. Often this is configured as a servlet filter. Have a look here - http://stackoverflow.com/questions/1139 ... zy-initial

Obviously some Spring is doing some work for you, but you need to understand what exactly it does and when.

--Hardy


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Mon Nov 07, 2011 6:33 am 
Newbie

Joined: Sat Nov 05, 2011 6:10 am
Posts: 12
You're right, i got this pattern in my web.xml file.

Code:
   <filter>
      <filter-name>JpaFilter</filter-name>
      <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
   </filter>


So, i guess that this pattern don't handle session for my piece of code because i'm not in a servletContext, i have to handle by myself. Thanks for the hint, i will check for that.


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Mon Nov 07, 2011 8:44 am 
Newbie

Joined: Sat Nov 05, 2011 6:10 am
Posts: 12
Ok so i built my own entityManage to manager my transaction, but the error is still the same :(
I really lost now ...

Code:
   private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaTutos");
   private static EntityManager em = emf.createEntityManager();
         EntityTransaction tx = em.getTransaction();
         Article article = new Article();
         tx.begin();
         article.setPage(page);
         article.setHeading(articleHeading.toString());
          article.setSubheading(articleSubHeading.toString());
         article.setAbstract_(articleAbstract.toString());
         article.setCategory("article");
         article.setFirstIllustrationId(0);
         article.setWordcount(totalWord);
         FullTextEntityManager fullTextEM = Search.getFullTextEntityManager(em);
         em.persist(article);
         fullTextEM.flushToIndexes();
         tx.commit();
         em.close();
         emf.close();



Code:
2011-11-07;14:35:52;AltoOCRImport;[ERROR];error while importing OCR Results
;org.hibernate.LazyInitializationException: could not initialize proxy - no Session
   at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
   at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
   at org.hibernate.search.util.HibernateHelper.unproxy(HibernateHelper.java:62)
   at org.hibernate.search.engine.impl.HibernateStatelessInitializer.unproxy(HibernateStatelessInitializer.java:48)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.buildDocumentFields(DocumentBuilderIndexedEntity.java:459)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.buildDocumentFields(DocumentBuilderIndexedEntity.java:552)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.buildDocumentFields(DocumentBuilderIndexedEntity.java:552)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.getDocument(DocumentBuilderIndexedEntity.java:443)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.createAddWork(DocumentBuilderIndexedEntity.java:380)
   at org.hibernate.search.engine.DocumentBuilderIndexedEntity.addWorkToQueue(DocumentBuilderIndexedEntity.java:358)
   at org.hibernate.search.engine.WorkPlan$PerEntityWork.enqueueLuceneWork(WorkPlan.java:456)
   at org.hibernate.search.engine.WorkPlan$PerClassWork.enqueueLuceneWork(WorkPlan.java:257)
   at org.hibernate.search.engine.WorkPlan.getPlannedLuceneWork(WorkPlan.java:150)
   at org.hibernate.search.backend.WorkQueue.prepareWorkPlan(WorkQueue.java:134)
   at org.hibernate.search.backend.impl.BatchedQueueingProcessor.prepareWorks(BatchedQueueingProcessor.java:124)
   at org.hibernate.search.backend.impl.PostTransactionWorkQueueSynchronization.flushWorks(PostTransactionWorkQueueSynchronization.java:127)
   at org.hibernate.search.backend.impl.TransactionalWorker.flushWorks(TransactionalWorker.java:112)
   at org.hibernate.search.impl.FullTextSessionImpl.flushToIndexes(FullTextSessionImpl.java:134)
   at org.hibernate.search.jpa.impl.FullTextEntityManagerImpl.flushToIndexes(FullTextEntityManagerImpl.java:121)
   at org.litis.plair.administration.AltoOCRImport.addXmlFile(AltoOCRImport.java:288)
   at org.litis.plair.administration.AltoOCRImport.run(AltoOCRImport.java:188)
   at org.litis.plair.service.old.ExecuteRunnerJob.execute(ExecuteRunnerJob.java:20)
   at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
   at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)


I don't understand why it said No session, as i opened one with tx.begin() ?


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Wed Dec 07, 2011 5:49 am 
Newbie

Joined: Wed Dec 07, 2011 5:27 am
Posts: 6
If you use OpenEntityManagerInViewFilter (in a common way) spring manages EM and syncs transaction. So you should take care about this and use also springs way... something like:

Code:
EntityManager entityManager = entityManagerFactory.createEntityManager();
TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(entityManager));
try {
    ....
} finally {
    EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(entityManagerFactory);
    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
}


see also http://blog.armstrongconsulting.com/?p=12 or ask in spring related forums.
regards mm


Top
 Profile  
 
 Post subject: Re: Yet another issue with Search using JPA, Hibernate, Spring
PostPosted: Fri Feb 24, 2012 5:44 am 
Newbie

Joined: Sat Nov 05, 2011 6:10 am
Posts: 12
thanks for your answer, it works great, but show to me another problem ... i open a new post :p


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 8 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.