Hibernate packageesToScan fails, but annotatedClasses works - spring

We have a new webapp that we are prepping for deployment. We changed how we include our jars, from just manually dumping them into the web-inf/lib to using eclipse's deployment assembly to move them from a common location into the web-inf/lib dynamically, creating one repository for our libs. This tactic works fine with everything but one jar...the one our hibernate entities are in.
The jar is there, we can see it. It's in the classpath, we can instantiate it. But when we run, we get an exception for unknown entity as if the annotations from the target entity were never run. When we replace our "packagesToScan" declaration with a "annotatedClasses" list, it works fine. Yet our packagesToScan looks right. I'd much rather use the flexible packagesToScan than has developers required to do the easy-to-forget step of declaring their classes each time.
Anyone have any idea why this might be?
spring config (the below shows all three at the same time, in reality we comment one in at a time):
<bean id="rptappSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="rptappDataSource" />
<!-- works -->
<property name="annotatedClasses">
<list><value>a.b.c.report.model.table.BOReportTask</value></list>
</property>
<!-- does not work -->
<property name="packagesToScan">
<list><value>a.b.c.report.model.table</value></list>
</property>
<!-- also does not work -->
<property name="packagesToScan" value="a.b.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
<prop key="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</prop>
<prop key="hibernate.bytecode.provider">javassist</prop>
<prop key="hibernate.show_sql">${hibernate.show.sql}</prop>
<prop key="format_sql">false</prop>
<prop key="use_sql_comments">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.default_schema">K702PRDR</prop>
</props>
</property>
</bean>
Exception:
Caused by: org.hibernate.hql.ast.QuerySyntaxException: BOReportTask is not mapped [from BOReportTask r where r.reportStatus = :status order by r.submissionTimestamp asc]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:181)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:313)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3353)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3237)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:724)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:575)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:292)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:235)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760)
at a.b.c.report.dao.hibernate.table.ReportTaskDao.fetchByStatus(ReportTaskDao.java:68)

So I recently rediscovered this post and thought I'd post the solution for posterity. When exporting the jars in RAD, the jar wizard has a checkbox called "Add Directory Entries" on the first page of the wizard. Check that. Without it, my packagesToScan reference, which was to a root of the package with the entities in it (since there is more than one package of entities), would not be found. It acted like there were no entitites. Checking this adds stuff to the manifest and causes the classes to be found by the annotation scanner.

Related

Spring 3.2 + JPA (with Hibernate 3.6) + Websphere 8 (JTA) not flushing/commiting some operations

I have some issues after changing my backend from Hibernate to JPA (+Hibernate). I am using Websphere and container transaction management through org.springframework.transaction.jta.WebSphereUowTransactionManager. Some operations don't behave as expected:
DELETE OPERATION: If I don't flush the EntityManager manually it won't issue the delete, nothing happens actually.
#Transactional
#Override
public void deleteApplication(Integer appId) {
Application app = appDAO.findOne(appId);
//em.flush(); to force the flush(), otherwise it doesn't do anything
appDAO.delete(app);
}
INSERT WITH CASCADE OPERATION: The Application entity has a N:M relation with Attribute. I try to persist an Application with some Attribute added to its Application.attributes List. Right after the appDAO.save() I see a insert into Application sentence. However, there are never any inserts for the cascaded Attributes into the join table. Again, I need to manually flush() the em to issue de sql statements left.
#Transactional
#Override
public Application createApplication(Application application) {
appDAO.save(application);
//em.flush(); Needed to force the cascade into the join table
return application
}
I have tried changing the transactionManager for a non-container-managed one (org.springframework.orm.jpa.JpaTransactionManager) and it works perfectly without needing to use manual flush.
I am not using the persistence.xml file, following the approach introduced in Spring 3.1 (jtaDataSource + packagesToScan). However I have also tried with the traditional config with a persistence.xml file and I experienced the same wrong behaviour.
¿Any suggestions?
My setup:
<bean id="mainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mainPersistenceUnit"/>
<property name="jtaDataSource" ref="mainDataSource"/>
<property name="packagesToScan" ref="packages-mainEntityManagerFactory"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WebSphereExtendedJTATransactionLookup</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.flush_before_completion">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
</bean>
<tx:annotation-driven order="0" />
<!-- Drives transactions using local JPA APIs -->
<bean name="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/>
In case someone has the same problem. The solution comes down to using
<prop key="hibernate.transaction.factory_class">org.hibernate.ejb.transaction.JoinableCMTTransactionFactory</prop>
instead of
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</prop>

Hibernate doesn't seem to be scanning for #Entity #Table

I've got two Spring Hibernate modules that I'm trying to combine. They have separate application contexts. In one hibernate uses xml mapping files while in the second module annotations are used to map the hibernate db tables.
Both modules seem to be scanned ok (service beans seem to be injected ok) except for the hibernate table scanning in the second table. One table occurs twice -- once in the xml mapping files and once in annotations but in different java packages with separated package scanning.
When I try to access the second module's table class in a hibernate select I get:
MappingException: Unknown entity: msg.entity: message
I tried substituting another annotated table entity in the hibernate query to check where the problem was mapping to the same table but I get the same MappingException so it seems like the problem is that hibernate is just not picking up any #Entity #Table annotations in the second module. But I tested this module on it's own and all the annotations did get picked up ok.
Could it be that the hibernate session factory is somehow being carried over from the calling module and masking the second module's session factory and its associated list of entities? Yet I'm not in a transaction in the calling method.
<context:component-scan base-package="msg"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceJmsMod"/>
<property name="packagesToScan" value="msg.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
Thanks for any help

Websphere, Spring, Hibernate, JAX-WS Global Transactions

I am attempting to write a demo of a JAX-WS service participating in a global transaction. This is a model my organization will be doing more of as time goes on and we need to figure it out, but I am struggling.
I have a WSDL service being invoked from a client (which is also in a Java EE servlet with the same config...in fact it is the same server, but I can see that it is calling out over the wire to itself). Both are updating their rows, and then I throw an exception but the service will not rollback.
I have annotated a method that invokes both a local DAO update and the WSDL service client with #Transactional(propagation=Propagation.REQUIRED). That service in turn invokes another method, also anotated in the same way, which in turn calls a dao method to do another db update.
app-config.xml:
<jee:jndi-lookup id="wsdlDataSource" jndi-name="${es.ds.jndi}" />
<bean id="wsdlSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="wsdlDataSource" />
<property name="packagesToScan" value="com.wsdl" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
<prop key="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</prop>
<prop key="hibernate.bytecode.provider">javassist</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.default_schema">k702prdr</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop>
<prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WebSphereExtendedJTATransactionLookup</prop>
<prop key="jta.UserTransaction">java:comp/UserTransaction</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.wsdl.db.DBTrans</value>
<value>com.wsdl.db.UsrTrans</value>
</list>
</property>
</bean>
<!-- END Data sources -->
<!-- BEGIN Hibernate config and dependencies -->
<bean id="transactionManager"
class="org.springframework.transaction.jta.WebSphereUowTransactionManager" >
</bean>
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
I have followed some tutorials that had me go in to the Services view and add the WSTRansaction policy sets and bindings o the client and service (both generated initially from the RAD wizard), and then again into Admin Console applications->application Types->Websphere enterprise apps->my app->Service provider/client policy sets and bindings. There I added WSTransaction to client and service respectively at the parent application level (the policy inherits down to the endpoint).
But at the end of the day, no rollback is happening. Help! What am I missing? What have I misconfigured?
(update) - I found how to turn on the websphere transaction trace log in the admin console. It says (edited for brevity):
No transaction context found
Exit
Entry parm0=Operation: isAlive
No transaction context from incoming request
getTransactionManager parm0=com.ibm.ws.tx.jta.TranManagerSet#306e306e
These messages come with a bunch of what appear to be inspections of objects, and they repeat many times. Okay, so I appear to not be sending a transaction context from my client. But I still don't understand why. Anyone?
(update 2) - I discovered that my WSTRansaction policy sets for the service and client was not set to share, so i set it to share via the wsdl, and the trace log now seems to indicate that it is finding the transaction context...or at least, it's no longer explicitly saying it can't as above. It is saying some things like the following that may or may not means what i think they mean (again, edited for brevity if there is something meaningful you are not seeing, tell me, there is alot more info in there):
Entry parm0=XATransactionWrapper# 5f175f17 XAResource: com.ibm.ws.rsadapter.spi.WSRdbXaResourceImpl#5b7d5b7d enlisted: falseHas Tran Rolled Back = false mcWrapper.hashCode()490085686 parm1=XARESOURCE_NOTASSOCIATED
xa_start with flag: 0=TMNOFLAGS
setResourceStatus parm0=from NONE to REGISTERED
[at this point I see a log stmt that indicates my first update in the service]
setResourceStatus parm0=from REGISTERED to COMPLETING_ONE_PHASE
**setResourceStatus parm0=from COMPLETING_ONE_PHASE to COMMITTED**
setResourceStatus parm0=from NONE to REGISTERED
[at this point I see a log stmt that indicates my second update, which is done in the client]
setResourceStatus parm0=from REGISTERED to COMPLETING
setResourceStatus parm0=from COMPLETING to ROLLEDBACK
[at this point I see the stack trace of the hardcoded exception I am throwing]
So it seems pretty clear that while the transaction manager now sees both the client and service transaction, it thought it was supposed to complete the transaction on the service side as soon as that part was done, not realizing it was supposed to continue. Somehow I triggered a premature commit I guess. Ideas?

hibernate.search.default.directory_provider in spring beans rather than persistence.xml

I am in a rather nasty situation. We use compass for Hibernate search integration with Lucene and have implemented database directory search (using JdbcDirectory) instead of FSDirectoryProvider, RAMDirectoryProvider etc.
The problem is that the directory provider is passed as a property inside the META-INF/persistence.xml like the one below:
<property name="hibernate.search.default.directory_provider" value="uk.company.package.JdbcDirectoryProvider" />
We need to pass the database details to the the JdbcDirectoryProvider as JdbcDirectory requires a datasource to be passed.
We are constructing the datasource (for the directory provider) in an unconventional way using a property file (in the class path) with the database and index details.
If we have uk.company.JdbcDirectoryProvider configured as a spring bean, we can inject the datasource. This works well with Tomcat but not with OAS or Weblogic as still as we are passing the directory_provider in the persistence.xml. Probably becasue the datasource is initialized by the spring (becasue of the way classloaders work in these app servers).
My question is how can we configure the hibernate.search.default.directory_provider directly inside aSpring bean instead of the persistence.xml?
The closest place is:
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
But it only takes three properties:
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
Solution
You could pass the hibernate properties in spring bean as jpaProperties
<property name="jpaProperties">
<props>
<prop key="hibernate.search.default.directory_provider">
uk.company.package.JdbcDirectoryProvider
</prop>
</props>
</property>
I found the solution.
You could pass the hibernate properties in spring bean as jpaProperties
<property name="jpaProperties">
<props>
<prop key="hibernate.search.default.directory_provider">
uk.company.package.JdbcDirectoryProvider
</prop>
</props>
</property>

Access Spring Web MVC Exception Resolver from Spring Security Context

I have a Spring Web MVC configuration with a SimpleMappingExceptionResolver in it to handle some access exceptions:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:defaultErrorView="uncaughtException">
<property name="exceptionMappings">
<props>
<prop key=".DataAccessException">dataAccessFailure</prop>
<prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop>
<prop key=".TypeMismatchException">resourceNotFound</prop>
<prop key=".MissingServletRequestParameterException">resourceNotFound</prop>
</props>
</property>
</bean>
I also have a Spring Security context configuration where I would like to handle some authentication related exceptions. Currently, I have an ExceptionMappingAuthenticationFailureHandler set up as follows:
<form-login authentication-failure-handler-ref="exceptionMapper" ... />
...
<bean id="exceptionMapper" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler" >
<property name="exceptionMappings">
<props>
<prop key=".CredentialsExpiredException">/resetPassword</prop>
<prop key=".BadCredentialsException">/login?failure=true</prop>
</props>
</property>
</bean>
I was thinking that it would be nice to consolidate these into a single exception handling configuration by moving the security mappings to the MVC configuration. My problem is that I don't know how to tell Spring Security that I want form-login's authentication-failure-handler to use the resolver.
I can't just add an id to SimpleMappingExceptionResolver because 1) authentication-failure-handler-ref expects a Handler, not a Resolver, and 2) any beans that are defined in the MVC configuration don't seem to be visible from the security context...
Thanks for any help!
To answer part 2) of your question, you can share bean definitions between configurations via the use of the <import resource="..."/> tag.
I'm not sure how successful you will be for part 1) (single exception resolver), because having looked at the API both classes are completely different - no shared interface. You may have to roll your own, using one of the classes as the platform and building the functionality of the other class into it.

Resources