I am using Spring+JPA+Hibernate
This is how my bean is defined
<bean id="entityManager"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaProperties">
<props>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
<.....other properties.......... >
</bean>
The generate_statics is only showing statistics for select queries.
How can we see statistics for inserts?
Is there a simple configuration that can be used to show all the statistics where we can see hibernate entity to query translation time and insert/update time to db?
I enabled the statistics using the following steps
Include the following dependency in your pom
org.lazyluke
log4jdbc-remix
0.2.7
replace your driver class with net.sf.log4jdbc.DriverSpy
enable the required in your log4j properties
log4j.logger.jdbc.sqlonly=OFF
log4j.logger.jdbc.sqltiming=INFO
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=ERROR
log4j.logger.jdbc.connection=ERROR
log4j.logger.jdbc.resultsettable=OFF
4.Add log4jdbc to the connection url
for example: i am using oracle db. so i changed the connection url from
jdbc:oracle:thin:#(hostname:port)
jdbc:log4jdbc:oracle:thin:#(hostname:port)
Related
I'm used to have persistence.xml in my projects in which I define the provider to use (hibernate in most cases).
However, I'm starting a new project in which it is mandatory to use Spring framework. I've seen some blogs describing the integration of Hibernate in Spring and I've understood that I should declare a session factory in spring's beans descriptor org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
All the examples I've seen don't mention the use of persistence.xml, persistence context, entity manager...
I'm not sure I understand this point, I always thought that Hibernate is just a provider of JPA unless the factory declared in application-context.xml is doing something in background. If it is the case, I would like to understand how it is working..
thanks in advance...
AnnotationSessionFactoryBean is Factory bean implemented by Spring to create Hibernate Session Factory and shared to Spring's Application Context.if you are planning to use Direct Hibernate ( in case you dont need persistent.xml / per-cont.xml / entityManager) you can provide the properties in AnnotationSession FactoryBean. and can be injected in Any DAO.
How ever if you are planing to wire through JPA. Then you need ( persistent and persistent-context and entity Manager). In order to do that you required three steps
1. declare / configure Spring's JPA Adapter to create EntityManager instance for you
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
Inside JPA Bean declaration provide details about your database and who is ORM provider such as ( hibernate /toplink / ....) in your case Hibernate
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle9Dialect"/>
</bean>
</property>
then Provide information about your persistent entity details in persistent.xml or some way
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
if you have any specific JPA properties then
<property name="jpaProperties">
<props>
<!-- <prop key="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</prop>
-->
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
</props>
</property>
Bottom line, Spring provies adapters to directly to Hibernate ( in that case your dont need Jpa files such as persistent.xml and so but you need hibernate related files like hbm files) or adapters to the JPA ( in that case you have provide details about who is JPA vendor and instrut spring how to connect to the JPA vendor).
Hope the above clarifies.
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
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.
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?
I need step by step guide to handle transactions in spring sqltemplate. Transaction handling has to be implemented in my project. Guide me. Need to use the transaction Managment with SqlTemplate.
I suggest you use #Transaction annotation than code it manually. You may follow example here. For its best practice, you may read here. If you plan to spend few hours to study Spring Data JPA, you almost no need to handle transaction manually for most cases.
Thanks.
if you are using Programmatic Transactions then use below
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
Programmatic means you have transaction management code surrounding your business code.
This gives extreme flexibility, but is difficult to maintain.
Declarative means you separate transaction management from the business code.
You can use annotations or XML based configuration.
Declarative Transaction Management allows to eliminate any dependencies on the transaction framework from the Java code.
The four participants to provide the transaction support are transaction manager, proxy factory, transaction interceptor, and a set of transaction attributes. below is an example
<bean id="boxOffice" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager"/></property>
<property name="target">
<ref bean="boxOfficeService"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop>
<prop key="allocate*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>