Rectangle 27 29

If you would like to keep Lazy Load and you are using Spring Boot, just add the config below in your application.properties:

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Awesome! This seems to have worked for me!

You are a genious, you are God in this Earth. Really thanks!!!!!

java - Spring Data JPA - "could not initialize proxy - no Session" - W...

java hibernate spring-boot spring-data-jpa c3p0
Rectangle 27 28

If you would like to keep Lazy Load and you are using Spring Boot, just add the config below in your application.properties:

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Awesome! This seems to have worked for me!

You are a genious, you are God in this Earth. Really thanks!!!!!

java - Spring Data JPA - "could not initialize proxy - no Session" - W...

java hibernate spring-boot spring-data-jpa c3p0
Rectangle 27 2

I think you need a <context:component-scan> in your appContext.xml. The <context:annotation-config> only activates annotations on beans already registered in the application context. The component-scan both scans packages for beans to register and activates annotations. Since you don't have a component-scan the @Transactional annotation is not wrapping the method in a transaction.

A good post on the difference between component-scann and annotation-config.

hibernate - Spring JPA TransactionRequiredException: no transaction is...

spring hibernate jpa
Rectangle 27 12

First, I make a quote of the Spring-Data JPA Documentation to justify why the delete method works in your case (I mean the option 2).

CRUD methods on repository instances are transactional by default. For reading operations the transaction configuration readOnly flag is set to true, all others are configured with a plain @Transactional so that default transaction configuration applies. For details see JavaDoc of CrudRepository

The delete method is actually a method of the CrudRepository. Your repository extends JpaRepository which extends CrudRespository, so it belongs to CrudRepository interface and according the quote above is transactional.

If you read the section Transactional Query Method you will see that is the same that the option 4 and you will know how to apply a custom transactional behavior for all methods of your repository. Also, the Example 61 of the documentation shows the same scenario that the option 3.

Now keep in mind that you aren't working with JDBC logic, in which case the database take care about the transactions, but within a ORM-based framework. ORM frameworks require a transaction in order to trigger the synchronization between the object cache and the database. So you must be aware and provide a transaction context for methods that do ORM logic like deleteByCustomerId.

By default @Transactional (I mean without any parameter) set propagation mode to REQUIREDand readOnly flag to false. When you invoke a method annotated within, a transaction is intialized if no-one exists. This is the reason of why the workaround of @LucasSaldanha (the same as example Using a facade to define transactions for multiple repository calls) and the option 4 works. Other wise, without a transaction, you fall in the thrown exception of the option 1.

I guess you are referring to Example 81 instead of Example 61.

java - Spring boot + Hibernate + JPA No transactional EntityManager av...

java spring hibernate jpa spring-boot
Rectangle 27 9

Spring's handling of the @PersistenceContext annotation does almost exactly what you're after, with one big difference: you always get a transaction scoped EntityManager and Spring injects always the same instance for the same thread, so you have kind of propagation and don't have to worry about thread-safety. But you'll never get an extended context this way! Believe me, Spring 3 and extended persistence context don't play well together, maybe this will change in Spring 3.1 but I'm afraid that's not in their focus. If you want to use an extended persistence context let Spring inject the EntityManagerFactory (via @PersistenceUnit annotation) and then create the EntityManager on your own. For propagation you'll have to either pass the instance as a parameter or store it in a ThreadLocal yourself.

What is the difference between manually creating EntityManager and injecting using @PersistenceContext. Do I get a different entity manager object every time I call entityManagerFactory.createEntityManager() or just the shared entity manager which is injected using the @PersistenceContext

entityManagerFactory.createEntityManager() creates a new application-managed instance while @PersistenceContext injects a container-managed instance. Check the JPA spec for the difference. In the specific case of the Spring framework the container-managed instance has transaction scoped and is bound to a thread local so each thread has at most one instance at the same time. (so there's no need for synchronization)

Spring JPA : Application managed persistence context with @Transaction...

spring jpa jpa-2.0
Rectangle 27 103

Hibernate is a JPA implementation, while Spring Data JPA is a JPA Data Access Abstraction. Spring Data offers a solution to GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.

Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC and overcome JDBC verbosity.

So does this mean that Spring Data JPA cannot exist of itself? That is, under the hood, it uses one of the JPA provider (like Hibernate, Eclipselink or any other JPA provider)?

That's right. Spring JPA requires a JPA provider.

java - What is the difference between Hibernate and Spring Data JPA - ...

java spring hibernate jpa spring-data-jpa
Rectangle 27 76

Hibernate is a JPA implementation, while Spring Data JPA is a JPA Data Access Abstraction. Spring Data offers a solution to GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.

Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC and overcome JDBC verbosity.

So does this mean that Spring Data JPA cannot exist of itself? That is, under the hood, it uses one of the JPA provider (like Hibernate, Eclipselink or any other JPA provider)?

That's right. Spring JPA requires a JPA provider.

java - What is the difference between Hibernate and Spring Data JPA - ...

java spring hibernate jpa spring-data-jpa
Rectangle 27 12

Seems EntityManager.getReference(Class, Object) returns "nothing" since we are in a new Transaction scope.

When use getOne and findOne methods Spring Data JPA - Stack Overflow

spring-data spring-data-jpa
Rectangle 27 2

Your transactional method storeEMail is being directly invoke by onMessage. The transactional behavior is implemented by a AOP proxy that wraps storeEMail. Since you are invoking storeEMail directly, the AOP proxy isn't invoked and you don't have a transaction. storeEMail needs to be invoked on an injected bean reference. You may want to reconsider your design.

java - Hibernate JPA and Spring javax.persistence.TransactionRequiredE...

java spring hibernate jpa transactional
Rectangle 27 2

Your transactional method storeEMail is being directly invoke by onMessage. The transactional behavior is implemented by a AOP proxy that wraps storeEMail. Since you are invoking storeEMail directly, the AOP proxy isn't invoked and you don't have a transaction. storeEMail needs to be invoked on an injected bean reference. You may want to reconsider your design.

java - Hibernate JPA and Spring javax.persistence.TransactionRequiredE...

java spring hibernate jpa transactional
Rectangle 27 74

What if I have a list of Embeddable? or element collection?

java - Spring Data JPA find by embedded object property - Stack Overfl...

java spring jpa spring-data spring-data-jpa
Rectangle 27 3

That's because your Runnable implementation is a Spring component, annotated with @Transactional, and that declarative transactions are achieved, in Spring, by wrapping the actual instance of the class inside a JDK interface-based proxy that handles the transaction. In consequence, the actual object that is autowired is not an instance of ThreadRetrieveStockInfoEuronext, but an instance of its interface, Runnable, that delegates to an instance of ThreadRetrieveStockInfoEuronext.

The usual fix to this problem is to autowire the interface instead of autowiring the concrete type. But in this case, this class shouldn't be a Spring component in the first place, and it shouldn't be transactional either. BTW, making it a prototype gives you the illusion that a new instance will be created each time submitRetrieveStockInfo() is called, but that's incorrect: a single instance is created and autowired into the RetrievelController singleton, and the same runnable is thus used for all the requests to the controller.

Just make ThreadRetrieveStockInfoEuronext a simple class, instantiate it using new, passing a Spring bean as argument, and make its run() method call a transactional method of that Spring bean:

@Transactional
@Component
public class ThreadRetrieveStockInfoEuronextImpl implements ThreadRetrieveStockInfoEuronext {
    @Override 
    void doSomething() { ... }
}

public class RetrievelController {

    @Autowired
    private ThreadRetrieveStockInfoEuronext threadRetrieveStockInfoEuronext;

    @RequestMapping(value = "/.retrieveStockInfo.htm", method = RequestMethod.POST)
    public ModelAndView submitRetrieveStockInfo(@ModelAttribute("retrieveStockInfoCommand") RetrieveStockInfoCommand command, BindingResult result, HttpServletRequest request) throws Exception {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                threadRetrieveStockInfoEuronext.doSomething();
            }
        };

        Global.poolMultiple.execute(runnable);
        return new ModelAndView(".retrieveStockInfo", "retrieveStockInfoCommand", command);
    }

Many thanks JB for your advise , The solution works perfectly !!

java - Spring JPA threads: IllegalArgumentException Exception - Stack ...

java spring hibernate jpa transactional
Rectangle 27 8

Looks like your someOtherMethod calls any other @Transactional component (some class with save method). And I think it has @Transactinal() (empty) annotation (which uses default bean named transactionManager).

TransactionInterceptor

Michail, your answer drove me into the right direction to find the root cause of my problem. My configuration is perfectly fine, the problem resides in Spring Data Jpa. I extended your answer to provide the explanation of this statement.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Working with Spring Data JPA, Hibernate and multiple transaction manag...

spring hibernate cxf spring-data-jpa transactionmanager
Rectangle 27 8

Looks like your someOtherMethod calls any other @Transactional component (some class with save method). And I think it has @Transactinal() (empty) annotation (which uses default bean named transactionManager).

TransactionInterceptor

Michail, your answer drove me into the right direction to find the root cause of my problem. My configuration is perfectly fine, the problem resides in Spring Data Jpa. I extended your answer to provide the explanation of this statement.

Working with Spring Data JPA, Hibernate and multiple transaction manag...

spring hibernate cxf spring-data-jpa transactionmanager
Rectangle 27 2

Maybe try using JpaTransactionManager instead. Maybe DatasourceTransactionManager isn't giving you the right transaction on methods you annotated with @Transactional

That's the point! As always the problem is too obvious to spot it straight away! I was following spring "Transaction Management" chapter of Spring framework reference where it isn't (at least for me when I read it) described clearly enough. Instead there is an example which uses DataSourceTransactionManager so I just do the same and didn't focus on it. After your post I looked to Spring in Action and there was vary nice table and graph showing when to use which transaction manager class. I have changed it to JpaTransactionManager and data is persisted to db without any problem. Thanks.

Also if you use Spring Roo, you can create a new project complete with JPA Hibernate setup, you can use it as a reference / sample project. Setting up a new Spring project from scratch is a tricky business

java - Spring + JPA transaction is created and commited but no result ...

java spring hibernate jpa transactions
Rectangle 27 3

You shouldn't use @Transactional on your test methods, I assume your service layer methods and/or DAO methods have that. Use @Rollback on your test methods so that your database will be cleared after running tests.

jpa - Transactional tests with Spring @ContextConfiguration - clearing...

spring jpa junit
Rectangle 27 7

You need to play your PROPAGATION_LEVEL and structure your service bean calls properly. If you're using @Transactional on your Service classes, what you described is normal, since the transaction demarcation happens on public methods level. So depending on the propagation level when entering the public method of the service bean, the transaction will either start, join an existing transaction, throw an exception or execute non-transactionally.

To have service methods execute in one transaction, its enough to have the propagation level set to support as you do in your GalleryService (providing that you don't override it on a method level), and call these methods from a single method of another service which is annotated @Transactional(propagation=Propagation.REQUIRED). Its important to have you're calls pass through a bean e.g. (galleryService.getPicture instead of local call getPicture), 'cause aspects that inject the transaction semantics work against a proxy that wraps the bean

@Service("exampleService")
@Transactional(propagation=Propagation.REQUIRED)
public class ExampleServiceImpl implements ExampleService {

  @Autowired
  private GalleryService galleryService;

  @Override
  public void singleTransaction() {
    galleryService.getPicture
    galleryService.getComments
  }

  ...
}

a brief PROPAGATION_LEVEL glossary

MANDATORY
          Support a current transaction, throw an exception if none exists.
NESTED
          Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
          Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
          Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
          Support a current transaction, create a new one if none exists.
REQUIRES_NEW
          Create a new transaction, suspend the current transaction if one exists.
SUPPORTS
          Support a current transaction, execute non-transactionally if none exists.

UPDATE with respect to the comment

No, but in my opinion its your best option. Consider the article http://www.ibm.com/developerworks/java/library/j-ts2/index.html. What I'm describing is whats referred to in the article as API layer strategy. Its defined as

The API Layer transaction strategy is used when you have coarse-grained methods that act as primary entry points to back-end functionality. (Call them services if you would like.) In this scenario, clients (be they Web-based, Web services based, message-based, or even desktop) make a single call to the back end to perform a particular request.

Now in the standard three-layer architecture you have the presentation, a business and a persistence layer. In simple words you can annotate your controllers, services or DAOs. Services are the ones holding the logical unit of work. If you annotate your controllers, they are part of your presentation layer, if your transactional semantics is there, and you decide to switch or add a non-http client (e.g. Swing client), you're bound to either migrate or duplicate your transaction logic. DAO layers should also not be the owners of transaction, 'the granularity of the DAO methods is much less than what is a business logical unit. I'm restraining from points like best-practice etc. but, if you're uncertain, choose your business (service) as your API transaction layer :)

You have numerous posts discussing this topic in all directions

very good and fun reading, many opinions and very context-dependant

Thank you for your explanation! But is combining service method calls into one service method the only way to handle those calls in one single transaction? This would result into one service method for each controller. I thought, that my problem arises from a wrong Spring configuration in my webapp.

Spring JPA transaction over multiple methods - Stack Overflow

spring jpa transactions
Rectangle 27 3

Transactions belong to Service layer. For example if you have HotelService, then the code would look like this:

@Service("hotelService")
@Transactional
public class HotelServiceImpl implements HotelService {
    @Autowired
    HotelDao hotelDao;

    // The rest of code omited ...
}

@AbhishekRanjan Well, that was just example. I usually define @Transactional(readOnly = true) before class and then if I need I define @Transactional(readOnly = false) before method.

java - Layer to use the @Transactional annotation in Spring Data JPA -...

java spring hibernate spring-data spring-data-jpa
Rectangle 27 3

Indeed to have a application managed persistence context, you need to somehow "hack" the @Transactional & @PersistenceContext infrastructure by providing them your own Entity Manager and do not let Spring create its own.

The key to achieve this is to play a little bit with the TransactionSynchronizationManager class to register your own Entity Manager to the thread local, Spring will use it to inject to the @PersistenceContext attribute.

I had this need some time ago for my own application and I've designed a small architecture based on Spring AOP to manage the extended persistence context.

Though im not currently in need for this feature anymore, i will try it out once i need it again in the future. Thank you !

Spring JPA : Application managed persistence context with @Transaction...

spring jpa jpa-2.0
Rectangle 27 10

In the upcoming version 1.5 (an RC is available in our milestone repositories) of Spring Data JPA you can simply redeclare the method in your repository interface and annotate it with @Query so that the execution as query method is triggered. This will then cause the named query to be looked up just as you're already used to from query methods:

interface UserJpaRepository extends PagingAndSortingRepository<User, Long> {

  @Query
  List<User> findAll();

  Page<User> findNameEqualsTest(Pageable pageable);
}
@Repository
  • Your @RestResource annotation configures the exporter in a way that will be the default anyway in Spring Data REST 2.0 (also in RC already). Ging forward, prefer @RestRepositoryResource, but as I said: the pluralization will be the default anyway.
  • We generally don't recommend to extend the store specific interfaces but rather use CrudRepository or PagingAndSortingRepository.

jpa - @NamedQuery override findAll in Spring Data Rest JpaRepository -...

spring jpa spring-data spring-data-jpa spring-data-rest