java - How to create non-transactional JUnit integration tests in Spring? -
an integration test class annotated with:
@runwith(springjunit4classrunner.class) @contextconfiguration(classes = integrationtestconfig.class)
it's not supposed run in transaction isn't marked @transactional
i'm getting errors when trying perform persist, merge etc. operations on entitymanager
, injected using @persistencecontext
:
no transactional entitymanager available
how can resolved?
edit: requested in comments, spring version 4.1.0.release , integrationtestconfig
below:
@enableaspectjautoproxy @enableasync @enablescheduling @enabletransactionmanagement @configuration public class integrationtestconfig { /** * override existing jpa data source bean test data source. * @return test data source */ @bean public datasource datasource() { final simpledriverdatasource datasource = new simpledriverdatasource(); datasource.setdriverclass(org.h2.driver.class); datasource.seturl("jdbc:h2:mem:test;mode=mysql;db_close_delay=-1;db_close_on_exit=false;init=create schema if not exists mydb"); datasource.setusername("sa"); datasource.setpassword(""); return datasource; } }
if sure never going call entitymanager.flush()
, obtain persistencecontext
follows:
@persistencecontext(type = persistencecontexttype.extended) private entitymanager entitymanager;
why needed? spring data jpa hands out called shared entitymanager
when @persistencecontext
annotation used (without attributes). full details available in javadocs org.springframework.orm.jpa.sharedentitymanagercreator
. class maintains lookup table entitymanager
methods flush
, merge
, persist
, refresh
, remove
required run inside transaction. so, time encounters method call not inside transaction, bails out.
the annotation @persistencecontext
has type
attribute can set 1 of persistencecontexttype.extended
or persistencecontexttype.transaction
, later being default. therefore, default @persistencecontext
causes sharedentitymanagercreator
transaction , bail out if none found.
using persistencecontexttype.extended
bypasses need check transaction when obtaining entitymanager
, therefore code should work.
flush
still cannot called without transaction because jpa providers require called within transactional context.
Comments
Post a Comment