Am new to SPRING with JPA techniques.
am trying to call the stored procedure which is written in mysql 5. when i am trying to get the data using stored procedure call it spewing exception.
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: query must begin with SELECT or FROM: call [call st_proc_getusers()]; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: query must begin with SELECT or FROM: call [call st_proc_getusers()]
my persistence.xml is
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="SPT3" transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/persistence-query.xml</mapping-file>
<class>com.spt3.pojo.Users</class>
<properties>
<property name="hibernate.dialect" value=">org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring_security" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="user" />
<property name="hibernate.connection.password" value="pass" />
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.query.factory_class" value="org.hibernate.hql.classic.ClassicQueryTranslatorFactory"/>
<property name="hibernate.query.substitutions" value="true 1, false 0"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
i tried code is
package com.spt3.dao;
import com.spt3.pojo.Users;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public class JpaUsersDao extends JpaDaoSupport {
public void getResultsByStoredProcedure() {
List list=(ArrayList)getJpaTemplate().execute(new JpaCallback() {
public List doInJpa(EntityManager em) throws PersistenceException {
javax.persistence.Query query=em.createQuery("call st_proc_getusers()"); // Here the procedure call
return query.getResultList(); // returning result list
}
});
}
}
Actually i don't know how to call the stored procedure using jpa template.
How can i call stored procedure from spring JPA?
please give the solution to get out from this issue.
Use EntityManager.createNativeQuery() instead. I don't think it's possible to call a stored procedure through a JPA query.
public List doInJpa(EntityManager em) throws PersistenceException {
javax.persistence.Query query=em.createNativeQuery("call st_proc_getusers()");
return query.getResultList();
}
You could also use #NamedNativeQuery.
Calling a stored procedure means executing some SQL statement. You can't do that with with a JPQL query (what you get in your code when you do em.createQuery(...)). You must create a native query that allows you to send native SQL to the database, execute it and get the results:
String query = "call st_proc_getusers(?)";
NativeQuery nq = em.createNativeQuery(query);
//the following line is necessary only if your stored procedure accepts a parameter:
nq.setParameter(1, "paramValue");
List<?> results = em.createNativeQuery(query).getResultList();
JPA 2.1 introduced support for stored procedures. You might want to give it a try instead of a native queries.
http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#createStoredProcedureQuery%28java.lang.String%29
Related
I have created an example - SPRING, JPA(EclipseLink persistence provider) with JTA Transaction Manager(JBoss 7). I have observed that all the data in database is being shown in UI properly for the read operations. But when it comes to save/update or delete operation the services layer is not committing the work to database. No exception is caught(I have checked the console/log too and also debugged the code where I can see entityManager.persist/remove is being invoked without any exception).
--Code Listing--
1. Datasource configuration in standalone.xml
<datasource jta="true" jndi-name="java:/mysql_customerdb3" pool-name="mysql_customerdb3_pool" enabled="true" use-java-context="true" use-ccm="true">
<connection-url>jdbc:mysql://localhost:3306/customerdb</connection-url>
<driver>mysql</driver>
<security>
<user-name>root</user-name>
<password>root</password>
</security>
<statement>
<prepared-statement-cache-size>10</prepared-statement-cache-size>
<share-prepared-statements>true</share-prepared-statements>
</statement>
</datasource>
<drivers>
<driver name="mysql" module="com.mysql">
<driver-class>com.mysql.jdbc.Driver</driver-class>
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
</driver>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
</drivers>
Database driver configuration in module.xml
persistence.xml
org.eclipse.persistence.jpa.PersistenceProvider
java:/mysql_customerdb3
com.springforbeginners.model.Customer
customerdispatcher-servlet.xml
<context:annotation-config />
<context:component-scan base-package="com.springforbeginners" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="loadTimeWeaver" ref="loadTimeWeaver" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
</bean>
<bean id="loadTimeWeaver" class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" >
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="java:jboss/TransactionManager"/>
<property name="userTransactionName" value="java:jboss/UserTransaction"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
CustomerServiceImpl.java
package com.springforbeginners.service;
import com.springforbeginners.dao.CustomerDAO;
import com.springforbeginners.model.Customer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerDAO customerDAO;
#Transactional
#Override
public void addCustomer(Customer customer) {
customerDAO.addCustomer(customer);
}
#Transactional
#Override
public List<Customer> listCustomer() {
return customerDAO.listCustomer();
}
#Transactional
#Override
public void removeCustomer(Integer customerId) {
customerDAO.removeCustomer(customerId);
}
}
CustomerDAOImpl.java
package com.springforbeginners.dao;
import com.springforbeginners.model.Customer;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#PersistenceContext(unitName="CustomerDetailsPU3")
private EntityManager entityManager;
#Override
public void addCustomer(Customer customer) {
entityManager.persist(customer);
}
#Override
public List<Customer> listCustomer() {
return entityManager.createQuery("select c from Customer c", Customer.class).getResultList();
}
#Override
public void removeCustomer(Integer customerId) {
Customer customer = (Customer) entityManager.getReference(Customer.class, customerId);
if (null != customer) {
entityManager.remove(customer);
}
}
}
I do not know what and where exactly is something missing. But with the above code the read operations are working as expected. Problem is with save operations. I have converted the above example to use non-JTA datasource(also modified standalone.xml for jta=false) and to use JpaTransactionManager as below
With non-JTA datasource and 'org.springframework.orm.jpa.JpaTransactionManager' all operations(read as well as save/update/delete) are working fine.
But the JTA version of my example is not working as expected(save operations not committing work to database). Any help/pointers appreciated.
Thanks
Prakash
James,
I will be running this application on JBoss. But one datasource on JBoss and other on Glassfish and transaction should span save operation on both datasources simultaneously. This is what I am trying to achieve. I have a web application including spring for service(data) layer currently running on JBoss.
As you said earlier - I will have two persistence.xmls one for JBoss and one for Glassfish. As I am doing this first time I was/am in doubt whether the transaction(that spans two datasources on different servers-in this case JBoss and Glassfish), can this be executed entirely by JBoss(in case if the entire business logic resides in serviceImpl class deployed on JBoss)? In this case I will be using JBoss transaction manager( property name="transactionManagerName" value="java:jboss/TransactionManager" ). Is this sufficient or do I need to similarly have Glassfish transaction manager too? Sorry if this has created the confusion.
Another question from me was that is there a provision for speifying jndi ports in persistence.xml/anywhere else?(Definitely I will have two different persistence.xmls and I will mention the target server as JBoss in one and as Glassfish in another).
Do we have a technique in spring by which business logic can be distributed across different servers like JBoss/Glassfish and still under one single transatcion? I did not know if this can be an option. Were u talking about this scenario in which it will require two different deployment scripts one for each server?
Thanks
Prakash
What is your persistence.xml?
Since you are using JTA, you must define the "eclipselink.target-server"="JBoss"
My persistence.xml(modified) now looks like below. Added target server property in persistence.xml. This solved the problem.
<persistence-unit name="CustomerDetailsPU3" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:/mysql_customerdb3</jta-data-source>
<class>com.springforbeginners.model.Customer</class>
<properties>
<property name="eclipselink.target-server" value="JBoss" />
</properties>
</persistence-unit>
Thanks
Prakash
I have a problem with my spring, hibernate app. I'm trying to make a login with spring security and im having little trouble geting my user account query to DB to work.
Problem is that my code will reach "test1" but it won't reach "test2" and since I'm not getting any errors to console and also app will continue running I have no clue what the problem might be.
When I press "login" button, I will directed to login failed page. Also I'll point out that I am new with spring and hibernate.
Anybody have any ideas what I'm doing wrong?
UserAccountService.java
package main.java.services;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import main.java.model.UserAccount;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service("userAccountService")
#Transactional
public class UserAccountService {
private EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager){
this. entityManager = entityManager;
}
public UserAccount get(Integer id)
{
Query query = entityManager.createQuery("FROM user_account as ua WHERE ua.id="+id);
return (UserAccount) query.getSingleResult();
}
public UserAccount get(String username)
{
System.out.println("test1");
Query query = entityManager.createQuery("FROM user_account as ua WHERE ua.username='"+username+"'");
System.out.println("test2");
return (UserAccount) query.getSingleResult();
}
public void add(UserAccount userAccount)
{
entityManager.persist(userAccount);
}
}
LoginService.java
package main.java.services;
import javax.annotation.Resource;
import main.java.model.UserAccount;
import main.java.security.CustomUserDetails;
import main.java.security.UserGrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
public class LoginService implements UserDetailsService{
#Resource(name="userAccountService")
private UserAccountService userAccountService;
public LoginService(){ }
public UserDetails loadUserByUsername(String username){
if (username != null && !username.equals("")){
UserAccount userAccount = userAccountService.get(username);
System.out.println(userAccount);
if (userAccount == null) {
return null;
}
GrantedAuthority grantedAuth = new UserGrantedAuthority(userAccount.getAuthority());
System.out.println(userAccount.getId() + userAccount.getAuthority()+userAccount.getPassword());
return new CustomUserDetails(userAccount.getId(), userAccount.getUsername(), userAccount.getPassword(), new GrantedAuthority[]{ grantedAuth });
} else {
return null;
}
}
}
hibernateContext.xml
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:property-placeholder location="/WEB-INF/jdbc.properties" />
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${jdbc.driverClassName}"
p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}"
p:password="${jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a JPA entityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
<property name="persistenceUnitName" value="hibernatePersistenceUnit" />
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="databasePlatform">
<value>${jdbc.dialect}</value>
</property>
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
For the first time of reading your post I can detect that your query is wrong...
Your query is an sql query. In this case you should use createNativeQuery()
instead of createQuery(). The proper query is (assuming that I do not know
you classes):
Query query = entityManager.createQuery("SELECT us FROM UserAccount as ua WHERE ua.username='"+username+"'");
where UserAccount is the name of the class, not the name of the table. Moreover
it is better using a prepared statement (google it) for passing arguments to the query.
I need to pass currently logged username to the DB Connection, because I want to trace user changes and store it in Oracle DB with correct user name. I am using Hibernate on my JBoss 5.1 and Oracle 11g database.
I think I need to do something like this (SOURCE):
try {
String e2eMetrics[] = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
e2eMetrics[OracleConnection.END_TO_END_CLIENTID_INDEX] = System.getProperty("user.name");
((OracleConnection) conn).setEndToEndMetrics(e2eMetrics, (short) 0);
} catch (SQLException sqle) {
// Do something...
}
Problem:
The problem is that I do not have an idea how/where to call it to pass some value to the connection. I mean where, in which moment I should inject this code, because I am using hibernate and EntityManagerFactory and I do not create connection manually, so I do not have access to connection object itself. I need to call it only once for whole user connection and remove username after connection release.
Expected goal:
My goal is to pass String (actual username) from java code or hibernate configuration to Oracle DB under 'client_info' column in v$session table, just after/during connection establishment which is done by hibernate.
I know that the value can be passed by DBMS_APPLICATION_INFO.SET_CLIENT_INFO() procedure and I even checked it with code below, but the main question is how to call it only once for whole connection at connection establishment in hibernate?
Working Test for passing value to the v$session table to 'client_info' column:
#Override
#Transactional
public void setDBClientInfo(String clientInfo) {
try {
Query query = em.createNativeQuery("{call SYS.dbms_application_info.set_client_info(:userName)}")
.setParameter("userName", clientInfo);
query.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
My Configuration:
spring-servlet.xml:
<!-- DataSource -->
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MynameDS" expected-type="javax.sql.DataSource" />
<!-- EntityManagerFactory -->
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<!-- TransactionManager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="MyUnitName" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>jdbc/MyNameDS</non-jta-data-source>
<class>com.mydomain.model.Assignment</class>
<class>com.mydomain.model.AuditLog</class>
<class>com.mydomain.model.Person</class>
<class>com.mydomain.model.Trial</class>
<class>com.mydomain.model.Violation</class>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
<property name="hibernate.validator.apply_to_ddl" value="false"/>
<property name="hibernate.validator.autoregister_listeners" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
Is it possible to do via hibernate configuration or via Java code?
Please help me to solve this problem..
I'm using JP2 in my current web project. My main database holds the main entities. To connect on this DB i defined a Persitence Unit with a JTA Datasource:
Persistance.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="MyPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>MyDB</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="ServerLogger"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
and the JTA Datasource defined in sun-resources.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_mydb_mypool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="5432"/>
<property name="databaseName" value="mydb"/>
<property name="User" value="myuser"/>
<property name="Password" value="mypass"/>
<property name="URL" value="jdbc:postgresql://localhost:5432/mydb"/>
<property name="driverClass" value="org.postgresql.Driver"/>
<property name="characterEncoding" value="UTF-8" />
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="MyDB" object-type="user" pool-name="post-gre-sql_mydb_mypoll"/>
</resources>
And this is how i access the database on my DAO classes (witch are #ManagedBeans and #SessionScoped):
#ManagedBean(name = "pageDao")
#SessionScoped
public class PageDao implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "MyPU")
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public List<PageEnt> getAll() { ... }
public PageEnt getOne(long pageId) { ... }
public void addPage(PageEnt newPage) throws RollbackFailureException, PreexistingEntityException, Exception { ... }
public PageEnt update(PageEnt page) throws RollbackFailureException, NonexistentEntityException, Exception { ... }
public void remove(PageEnt page) throws RollbackFailureException, Exception { ... }
}
One of entities (customer) has properties for connecting on a separate (per-customer) database, witch are defined in run-time. These properties includes:
Databse name
Host and port
User and Password
My question are:
How do I efficiently create a database connection in run-time?
How can I create a new EntityManager from container-managed resources if there is no per-customer PersistanceUnit and Datasources defined (witch are defined at deploy-time)?
If i have to manually deal with the EntityManagerFactory (witch, as i learned in college, is a heavy and expansive object), how do I efficiently do that? Is there a good-practice or pattern?
How would the DAO pattern work? How do my DAO class will get the EntityManager?
Big thanks from Brazil.
It is possible to switch between multiple data sources at run time. It is provided by Spring AbstractRoutingDataSource . It is required to override the #determineCurrentLookupKey() method which will return a key to decide the specific datasource that is needed to be connected. Also there should be spring configuration that maps each of the possible keys and the corresponding data sources that are to be connected. Some thing like
<jee:jndi-lookup id="DataSource_Client1" jndi-name="DataSource_Client1" />
<jee:jndi-lookup id="DataSource_Client2" jndi-name="DataSource_Client" />
<bean id="DynamicDataSource" class="concrete implementation class name of AbstractRoutingDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="Client1" value-ref="DataSource_Client1" />
<entry key="Client2" value-ref="DataSource_Client2" />
</map>
</property>
</bean>
A possible reference to this Dynamic DataSource
Hope this answers one of your questions
I found some strange behavior when using nested Spring transactions: when, in the same class, a method annotated as #Transactional calls another method also annotated as #Transactional the second annotation is not used.
Let's consider the following class:
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
final Main main = context.getBean(Main.class);
// First Op
System.out.println("Single insert: " + main.singleInsert());
// Second Op
main.batchInsert();
// Third Op
main.noTransBatchInsert();
}
#PersistenceContext
private EntityManager pm;
#Transactional(propagation=Propagation.REQUIRED)
public void batchInsert() {
System.out.println("batchInsert");
System.out.println("First insert: " + singleInsert());
System.out.println("Second insert: " + singleInsert());
}
public void noTransBatchInsert() {
System.out.println("noTransBatchInsert");
System.out.println("First insert: " + singleInsert());
System.out.println("Second insert: " + singleInsert());
}
#Transactional(propagation=Propagation.REQUIRES_NEW)
public int singleInsert() {
System.out.println("singleInsert");
Pojo p = new Pojo();
pm.persist(p);
return p.getId();
}
}
The entity if the following class:
#Entity
public class Pojo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Override
public String toString() {
return "Pojo: " + id;
}
public int getId() {
return id;
}
}
and the String parts applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<tx:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="MyPersistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
and the configuration class (I could have merge this in applicationContext.xml).
#Configuration
#ImportResource("/META-INF/applicationContext.xml")
public class Config {
#Bean
public Main main() {
return new Main();
}
}
For completeness the persistence.xml file:
<persistence 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_2_0.xsd" version="2.0">
<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:mem:TestDSJPA2;DB_CLOSE_DELAY=-1;LOCK_MODE=0" />
<!--<property name="hibernate.connection.url" value="jdbc:h2:mem:TestDSJPA2;DB_CLOSE_DELAY=-1;LOCK_MODE=0" />-->
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.connection.autocommit" value="false"/>
<property name="hibernate.c3p0.min_size" value="5" />
<property name="hibernate.c3p0.max_size" value="20" />
<property name="hibernate.c3p0.timeout" value="300" />
<property name="hibernate.c3p0.max_statements" value="50" />
<property name="hibernate.c3p0.idle_test_period" value="3000" />
</properties>
</persistence-unit>
</persistence>
So in the main class, the first operation is performed as expected that is in a new transaction. The output (including some DEBUG messages) is:
DEBUG o.h.transaction.JDBCTransaction - begin
singleInsert
DEBUG o.h.transaction.JDBCTransaction - commit
Single insert: 1
The second operation gives the following output:
batchInsert
singleInsert
DEBUG o.h.transaction.JDBCTransaction - begin
First insert: 2
singleInsert
Second insert: 3
DEBUG
This is not what I expected since in annotating singleInsert with #Transactional(propagation=Propagation.REQUIRES_NEW) I would expect a new transaction to be created for every call which is not what's happening since the same top level transaction is used for both insertion.
The third operation fails as well as no transaction is created at all:
noTransBatchInsert
singleInsert
DEBUG o.h.e.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
First insert: 0
singleInsert
DEBUG o.h.e.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
Second insert: 0
In the #Configuration beans Spring ensures that calls to the method on the same class are proxified which is obviously not happening here. Is there a way do change this behavior?
This behavior is the documented behavior of Spring when using the proxy mode for AOP. It can be changed by switching to the aspectj mode which perform code instrumentation either on compilation or at runtime.
This is not specifically a problem with #Transactional. It is due to the configuration of your <tx:annotation-driven/>.
Spring uses two different AOP mechanisms: JDK dynamic proxies or CGLIB. JDK dynamic proxies is the default and it works through the use of interfaces at run-time. CGLIB works by generating subclasses at compile-time. If you specify <tx:annotation-driven proxy-target-class="true"/>, Spring will use CGLIB, and your second #Transactional will fire.
You can read more about the subject here.
The default advice mode for processing #Transactional annotations is
proxy, which allows for interception of calls through the proxy only.
Local calls within the same class cannot get intercepted that way. For
a more advanced mode of interception, consider switching to aspectj
mode in combination with compile-time or load-time weaving.
Taken from Spring reference. https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#tx-propagation-nested