I am trying to connect two database using spring boot JPA
Application.properties :
Application configuration.
server.port=8102
# Hibernate configuration.
spring.jpa.show-sql = true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
#spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServer2012Dialect
app.datasource.cardHolder.url=jdbc:sqlserver://server:22;databaseName=DB1
app.datasource.cardHolder.username=name
app.datasource.cardHolder.password=psw
app.datasource.cardHolder.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
server.path=F:\\
app.datasource.card.url=jdbc:sqlserver://server:22;databaseName=DB2
app.datasource.card.username=uname
app.datasource.card.password=psw
app.datasource.card.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.open-in-view=false
# Logging configuration.
logging.level.com.springboot.storedprocedure=DEBUG
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %msg%n
com.app.configuration
CardConfig :
#Configuration
#EnableJpaRepositories(basePackages = "com.app.repository",
entityManagerFactoryRef = "cardEntityManagerFactory",
transactionManagerRef= "cardTransactionManager")
public class CardDataSourceConfiguration {
#Bean
#Primary
#ConfigurationProperties("app.datasource.card")
public DataSourceProperties cardDataSourceProperties() {
return new DataSourceProperties();
}
#Primary
#Bean
#ConfigurationProperties("app.datasource.card.configuration")
public DataSource cardDataSource() {
return cardDataSourceProperties().initializeDataSourceBuilder()
.type(BasicDataSource.class).build();
}
// #PersistenceContext(unitName = "first")
#Primary
#Bean(name = "cardEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean cardEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(cardDataSource())
.packages(Card.class)
.build();
}
#Primary
#Bean
public PlatformTransactionManager cardTransactionManager(
final #Qualifier("cardEntityManagerFactory") LocalContainerEntityManagerFactoryBean cardEntityManagerFactory) {
return new JpaTransactionManager(cardEntityManagerFactory.getObject());
}
}
CardHolder :
#Configuration
#EnableJpaRepositories(basePackages = "com.app.repository2",
entityManagerFactoryRef = "cardHolderEntityManagerFactory",
transactionManagerRef= "cardHolderTransactionManager")
public class CardHolderDataSourceConfiguration {
#Bean
#ConfigurationProperties("app.datasource.cardholder")
public DataSourceProperties cardHolderDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties("app.datasource.cardholder.configuration")
public DataSource cardholderDataSource() {
return cardHolderDataSourceProperties().initializeDataSourceBuilder()
.type(BasicDataSource.class).build();
}
// #PersistenceContext(unitName = "second")
#Bean(name = "cardHolderEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean cardHolderEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(cardholderDataSource())
.packages(CardHolder.class)
.build();
}
#Bean
public PlatformTransactionManager cardHolderTransactionManager(
final #Qualifier("cardHolderEntityManagerFactory") LocalContainerEntityManagerFactoryBean cardHolderEntityManagerFactory) {
return new JpaTransactionManager(cardHolderEntityManagerFactory.getObject());
}
}
CardConfi is set the JPARepository properly and return data based on DB2 but same way i have added EntityManger in CardHolderRepository like below,
#Entity
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(name= "callSP", procedureName= "cardmsSP", parameters= {
#StoredProcedureParameter(mode= ParameterMode.IN, name= "Name", type= String.class)
})
})
public class CardHolder implements Serializable {
//getter setter
}
com.app.repository2
#Repository
public class CardHolderDao {
#Autowired
SPRepository spRep;
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
public List<CardHolder> gecardtHolderList (String input) {
return em.createNamedStoredProcedureQuery("cardmsSP").setParameter("Name", input).getResultList();
}
}
com.app.repository2
public interface SPRepository extends JpaRepository<CardHolder, Long>, JpaSpecificationExecutor<CardHolder>{
}
Problem is that EntityManager em is always pointing to DB2 instead of DB1. where am I doing mistake?
You should set EntityManagerFactoryBuilder#persistenceUnit
#Bean(name = "cardHolderEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean cardHolderEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(cardholderDataSource())
.packages(CardHolder.class)
.persistenceUnit("cardHolderEntityManager") // !!!
.build();
}
And then
#PersistenceContext(unitName = "cardHolderEntityManager")
EntityManager em;
Related
I am trying to connect with two databases in Spring Boot. But two domains are creating in the primary Database. I uploaded my code. If anyone knows. I am not getting any console errors.But two domains creating in primary DB.
May I know what is region behind this?
(First Databse)
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "dbEntityManagerFactory", transactionManagerRef = "dbTransactionManager", basePackages = {
"com.multipledatasources.db.domain", "com.multipledatasources.db.repository" })
public class DBConfigure {
#Autowired
private DatabaseSettings databaseSettings;
#Bean
#Primary
#ConfigurationProperties("spring.datasource1")
public DataSourceProperties productProperties() {
return new DataSourceProperties();
}
#Primary
#Bean(name = "DB")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
return dataSourceProperties.initializeDataSourceBuilder().build();
}
#Primary
#Bean(name = "dbEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean dbEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("DB") DataSource DBDataSource) {
Map<String, String> map = databaseSettings.setting();
return builder.dataSource(DBDataSource)
.packages("com.multipledatasources.db.domain", "com.multipledatasources.db.repository").properties(map)
.persistenceUnit("DB").build();
}
#Primary
#Bean(name = "dbTransactionManager")
public PlatformTransactionManager dbTransactionManager(
#Qualifier("dbEntityManagerFactory") EntityManagerFactory dbEntityManagerFactory) {
return new JpaTransactionManager(dbEntityManagerFactory);
}
(Second Database)
#EnableTransactionManagement
#EnableJpaRepositories(transactionManagerRef = "sysTransactionManager", entityManagerFactoryRef = "sysEntityManagerFactory", basePackages = {
"com.multipledatasources.sys.domain", "com.multipledatasources.sys.repository" })
public class SysConfigure {
#Autowired
private DatabaseSettings databaseSettings;
#Bean
#ConfigurationProperties("spring.datasource2")
public DataSourceProperties sysProperties() {
return new DataSourceProperties();
}
#Bean(name = "sys")
public DataSource sysDataSource(DataSourceProperties dataSourceProperties) {
return dataSourceProperties.initializeDataSourceBuilder().build();
}
#Bean(name = "sysEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean sysEntityManagerFactory(
EntityManagerFactoryBuilder entityManagerFactory, #Qualifier("sys") DataSource dataSource) {
Map<String, String> map = databaseSettings.setting();
return entityManagerFactory.dataSource(dataSource).properties(map)
.packages("com.multipledatasources.sys.domain", "com.multipledatasources.sys.repository")
.persistenceUnit("sys").build();
}
#Bean(name = "sysTransactionManager")
public PlatformTransactionManager sysTransactionManager(
#Qualifier("sysEntityManagerFactory") EntityManagerFactory sysEntityManagerFactory) {
return new JpaTransactionManager(sysEntityManagerFactory);
}
(Setting class)
Map<String, String> map = new HashMap<>();
map.put(AvailableSettings.SHOW_SQL, "true");
map.put(AvailableSettings.HBM2DDL_AUTO, "update");
map.put(AvailableSettings.DIALECT, "org.hibernate.dialect.MySQL5InnoDBDialect");
return map;
}
(Application.properties File)
server.port=4456
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.generate-ddl=true
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource1.url=jdbc:mysql://localhost:3306/DB?useSSL=false
spring.datasource1.username=root
spring.datasource1.password=sarat
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource2.url=jdbc:mysql://localhost:3306/sys?userSSL=false
spring.datasource2.username=root
spring.datasource2.password=sarat
Project Strectures
I having a configuration problem that cause the error below. I know there are a tons of similar problem but I read a lot of answer that stackoverflow suggest with my title but I don't find the right answer yet.
Description:
Field collaborateurJpaRepository in com...infrastructure.persistence.user.UserRepositoryImpl required a bean of type 'com...infrastructure.persistence.jurisdiction.CollaborateurJpaRepository' that could not be found.
Action:
Consider defining a bean of type 'com...infrastructure.persistence.jurisdiction.CollaborateurJpaRepository' in your configuration.
Before to give some details of the code, I think it could be nice that I describe you brievly the context.
I work on a client project which has 8 maven modules (DDD methods) because at the end of the year 4 modules will be separate in an other server.
Recently we create a second oracle database so I had to create multiple configuration to refer to the good dataSource.
I think the problem is due to bad datasource configuration that block the bean spring instanciation.
We are using spring boot version 1.5.7.release.
First Infrastructure configuration
#Configuration
#ComponentScan(basePackages = "com...jade")
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "jadeEntityManager", transactionManagerRef = "jadeTransactionManager")
#EntityScan(basePackages = { "com...jade", "org.springframework.data.jpa.convert.threeten" })
#Profile({"ARA_JADE_CONF", "LOCAL_JADE_CONF"})
public class InfrastructureConfig {
private final static int JDBC_FETCH_SIZE = 1000;
#Autowired
private Environment environment;
#Bean
public LocalContainerEntityManagerFactoryBean jadeEntityManager() throws SQLException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSourceJade());
em.setPackagesToScan(new String[] {"com...jade"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
#Primary
public OracleDataSource dataSourceJade() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(environment.getProperty("db.datasource.jade.username"));
dataSource.setPassword(environment.getProperty("db.datasource.jade.password"));
dataSource.setURL(environment.getProperty("db.datasource.jade.url"));
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean(name="jdbcTemplateJade")
public JdbcTemplate jdbcTemplateJade() throws SQLException {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceJade());
jdbcTemplate.setResultsMapCaseInsensitive(true);
jdbcTemplate.setFetchSize(JDBC_FETCH_SIZE);
return jdbcTemplate;
}
#Bean
public PlatformTransactionManager transactionManager() throws SQLException{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(jadeEntityManager().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
} ...
Seconde Infrastructure configuration
#Configuration
#ComponentScan(basePackages = "com.bnpparibas.sit.risk.art")
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "artEntityManager", transactionManagerRef = "artTransactionManager")
#EntityScan(basePackages = { "com...art", "org.springframework.data.jpa.convert.threeten" })
#Profile({"LOCAL_ART_CONF,'ARA_ART_CONF"})
public class ArtInfrastructureConfig {
private final static int JDBC_FETCH_SIZE = 1000;
#Autowired
private Environment environment;
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean artEntityManager() throws SQLException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSourceArt());
em.setPackagesToScan(new String[] {"com...art.infrastructure.persistence"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
#Primary
public OracleDataSource dataSourceArt() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(environment.getProperty("db.datasource.art.username"));
dataSource.setPassword(environment.getProperty("db.datasource.art.password"));
dataSource.setURL(environment.getProperty("db.datasource.art.url"));
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean
#Primary
public PlatformTransactionManager artTransactionManager()throws SQLException{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(artEntityManager().getObject());
return transactionManager;
}
#Bean
#Primary
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}...
Interface link to Entity.
#DDD.Repository
#Repository
public interface CollaborateurJpaRepository extends CrudRepository<Collaborateur,String>{
#Query("FROM ART_PARAM.ART_USER u WHERE u.refogUID = :uid")
Collaborateur findCollaborateurById(#Param("uid") String uid);
}
Class that contain the autowired interface to retrieve some data of the second database.
#DDD.RepositoryImpl
#Repository
#Primary
public class UserRepositoryImpl implements UserRepository {
#Autowired
private CollaborateurJpaRepository collaborateurJpaRepository;
#Override
//#Cacheable(cacheNames = CacheConfig.CACHE_JURIDICTION, key = CacheConfig.CACHE_KEY_UTILISATEUR_ID)
#Transactional("entityManagerFactoryArt")
public User retrieveUser(UserId userId) {
if(userId.getValue() == null) {
return null;
} else {
Collaborateur collaborateur = collaborateurJpaRepository.findOne(userId.getValue());
return new User(collaborateur.getRefogUID(),collaborateur.getRefogFirstName(),collaborateur.getRefogLastName(),collaborateur.getProfile(),collaborateur.isActiveUser(),collaborateur.isBankingSecrecy());
}
}
I want to use Playframework 2.5 together with Spring and JPA. I found the following template https://github.com/jamesward/play-java-spring where it works perfectly, unfortunately it’s not for Playframework 2.5. So I decided to adapt this template and create my own one for Playframework 2.5. However, my entitymanager in my controller Application is still null. What am I doing wrong? My code looks like the following:
AppConfig.java
package config;
#Configuration
#ComponentScan({"daos","services","controllers","models"})
public class AppConfig {
}
DataConfig.java
package config;
#Configuration
#EnableTransactionManagement
public class DataConfig
{
#Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPackagesToScan("models");
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaPropertyMap(new HashMap<String, String>(){{
put("hibernate.hbm2ddl.auto", "create-drop");
put("hibernate.dialect","org.hibernate.dialect.PostgreSQLDialect");
}});
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(entityManagerFactory());
return transactionManager;
}
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
return dataSource;
}
}
Global.java
package config;
#Singleton
#Configuration
public class Global
{
private ConfigurableApplicationContext context;
#Inject
public Global(ApplicationLifecycle lifecyle)
{
this.context = new AnnotationConfigApplicationContext(AppConfig.class, DataConfig.class);
lifecyle.addStopHook(()-> {
context.close();
return CompletableFuture.completedFuture(null);
});
}
}
Application.java
package controllers;
#Controller
#Transactional
#Component
public class Application extends play.mvc.Controller
{
#PersistenceContext
private EntityManager em;
#Transactional
public Result index()
{
System.out.println("******************* EM " + this.em +" *************************");
return ok(index.render());
}
}
Thank you for your help!
I am using JPA in my application, and it works once I query for objects, however it throw error javax.persistence.TransactionRequiredException: No transactional EntityManager available once I tried to save or update an object.
This is the java configuration:
#Configuration
#EnableTransactionManagement(proxyTargetClass = true)
#PropertySource("classpath:dao.properties")
public class JpaConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
.....................
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", ...........)
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setJpaProperties(jpaProperties);
entityManagerFactoryBean.setPackagesToScan("com....");
return entityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
Note I use proxyTargetClass = true in the #EnableTransactionManagement, since I do not want to create the useless interfaces in my application.
And this is the concrete implemention of the dao:
#Transactional
#Repository
public abstract class AbstractJPADao<I, E> {
#Autowired
#PersistenceContext
protected EntityManager entityManager;
private Class<E> type;
public AbstractJPADao() {
type=....
}
#Override
public Result<E> find(I id) {
E e = entityManager.find(type, id);
return Result.newInstance().setContent(e);
}
#Override
public Result<E> find(Map<String, Object> condition) {
Query q = entityManager.createQuery(".......));
return Result.newInstance().setContent(q.getResultList());
}
#Override
public E save(E element) {
entityManager.persist(element);
return element;
}
#Override
public E update(E element) {
entityManager.merge(element);
return element;
}
#Override
public void delete(E element) {
entityManager.remove(element);
}
}
#Repository
#Transactional
public class DepartmentDao extends AbstractJPADao<String, Department> {
#Override
protected String selectCause(Map<String, Object> condition) {
return "";
}
}
And the controller as the client of the dao:
#Controller
#RequestMapping("/api/deps")
public class DepartmentCtrl {
#Autowired
private DepartmentDao departmentDao;
#RequestMapping(value = "", method = RequestMethod.POST)
public Result create(#Valid Department department, BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
departmentDao.save(department);
return Result.newInstance().setContent(department);
}
throw new RuntimeException("...");
}
}
Is there anything wrong?
dao.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/proj
jdbc.username=root
jdbc.password=
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
#hibernate.ejb.naming_strategy=true
hibernate.show_sql=true
hibernate.format_sql=true
Try renaming method transactionManager to txManager in the class JpaConfig
Autowiring goes by the name txManager
Edit
Also the framework could be expecting a no argument method for txManager. Can you try changing to
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
As noticed Tiny, you have two annotations #Autowired and #PersistenceContext over the protected field of type EntityManager in AbstractJPADao.
Try removing #Autowired. #PersistenceContext is enough to inject the EntityManager.
I'm using spring-jpa. I have 2 tests.
#Test
#Transactional
public void testFindAll() {
List<Engine> eList = engineService.findAll();
Engine e = eList.get(0); //this engine id=3
List<Translation> tList = e.getTranslations();
for(Translation t : tList) {
...
}
}
This method fails with this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize
a collection of role: xxx.Engine.translations, could not initialize
proxy - no Session
However, this method works just fine:
#Test
#Transactional
public void testFindOne() {
Engine e = engineService.findOne(3);
List<Translation> tList = e.getTranslations();
for(Translation t : tList) {
...
}
}
Why translation list is successfully loaded in one case, but not in another?
EDIT: service/repo code:
public interface EngineRepository extends JpaRepository<Engine, Integer>
{
}
.
#Service
#Transactional
public class EngineService
{
#Autowired
private EngineRepository engineRepository;
public List<Engine> findAll()
{
return engineRepository.findAll();
}
public Engine findOne(Integer engId)
{
return engineRepository.findOne(engId);
}
}
.
public class Engine implements Serializable {
...
#OneToMany
#JoinColumn(name="ID", referencedColumnName="TRAN_ID", insertable=false, updatable=false, nullable=true)
#LazyCollection(LazyCollectionOption.EXTRA)
private List<Translation> translations;
...
}
Config:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"xxx.dao"})
#ComponentScan(basePackages = {"xxx.dao", "xxx.service", "xxx.bean"})
#PropertySource("classpath:application.properties")
public class SpringDataConfig {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(environment.getProperty("db.url"));
dataSource.setDriverClassName(environment.getProperty("db.driverClass"));
dataSource.setUsername(environment.getProperty("db.username"));
dataSource.setPassword(environment.getProperty("db.password"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL);
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getProperty("hibernate.showSQL"));
properties.put("hibernate.format_sql", environment.getProperty("hibernate.formatSQL"));
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan("xxx.model");
entityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter);
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I think the problem here is that the session gets closed after the first line in the first case. You should check out the JpaRepository implementation of findAll().
Integration Testing with Spring
It seems you're failing to provide a Spring Context within your TestCase, what that means? The #Transactional is being ignored. Therefore you end up with the closed session exception, because there is no transaction.
Take a look how to configure a TestCase with a Spring Context here
#RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
#ContextConfiguration(classes = {AppConfig.class, TestConfig.class})
public class MyTest {
#Autowired
EngineService engineService;
#Test
#Transactional
public void testFindOne() {}
#Test
#Transactional
public void testFindAll() {}
}