here are my 3 classes:
#Configuration //Marks this class as configuration
//Specifies which package to scan
#ComponentScan({"pl.jpet"})//,"pl.dup"})
//Enables Spring's annotations
#EnableWebMvc
//#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class Config {
#Resource
private Environment env;
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/wikidb");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
#Bean
#Autowired
public EntityManagerFactory entityManagerFactory(BasicDataSource dataSource) {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
vendorAdapter.setDatabase(Database.MYSQL);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setDataSource(dataSource);
factory.setPersistenceUnitName("wikidb");
factory.setPackagesToScan("pl.jpet");
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
#Autowired
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
JpaDialect jpaDialect = new HibernateJpaDialect();
txManager.setEntityManagerFactory(entityManagerFactory);
txManager.setJpaDialect(jpaDialect);
return txManager;
}
----------------------------------------------------------------------
package pl.jpet.model;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Data
#Table(name="zrobmitabele")
public class TestModel {
#Id
#Column(name = "name", nullable = false)
private String name;
}
-----------------------------------------------------------------------------
#Transactional
#RestController
#RequestMapping("/una")
public class UnauthenticatedController {
#PersistenceContext
private EntityManager em;
#Transactional
#RequestMapping(method = RequestMethod.GET,value="/checkLogin")
public ResponseEntity<String> checkLogin() throws IOException {
TestModel test = new TestModel();
test.setName("KUBA");
em.persist(test);
return new ResponseEntity<String>(HttpStatus.OK);
}
}
I'm getting this info on start "INFO [org.hibernate.cfg.Environment] (MSC service thread 1-1) HHH000206: hibernate.properties not found" but still it's not crushing, even after I'm making call to "/una" service it's not throwing anything - Guess there's something wrong with my Config class but i have no idea what, anyone ?
I missed #EnableTransactionManagement on my config class
#_#
Related
I'm trying to configure Spring Boot to use 2 datasources using JNDI:
application.properties:
spring.production.datasource.jndi-name=java:/global/production_gateway
spring.production.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.production.datasource.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.production.datasource.jpa.show-sql = true
spring.production.datasource.jpa.hibernate.ddl-auto = update
spring.warehouse.datasource.jndi-name=java:/global/production_warehouse
spring.warehouse.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.warehouse.datasource.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.warehouse.datasource.jpa.show-sql = true
spring.warehouse.datasource.jpa.hibernate.ddl-auto = update
Primary datasource:
#Configuration
#EnableJpaRepositories(
basePackages = "org.datalis.plugin.production.entity",
entityManagerFactoryRef = "productionEntityManager",
transactionManagerRef = "productionTransactionManager"
)
#EnableTransactionManagement
public class ContextProductionDatasource {
#Primary
#Bean(name = "productionDataSourceProperties")
#ConfigurationProperties(prefix="spring.production.datasource")
public JndiPropertyHolder productionDataSourceProperties() {
return new JndiPropertyHolder();
}
#Primary
#Bean(name = "productionDataSource")
#ConfigurationProperties(prefix="spring.production.datasource")
public DataSource productionDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
DataSource dataSource = dataSourceLookup.getDataSource(productionDataSourceProperties().getJndiName());
return dataSource;
}
#Primary
#Bean(name = "productionEntityManager")
public EntityManager productionEntityManager(EntityManagerFactory emf) {
return emf.createEntityManager();
}
#Primary
#PersistenceContext(unitName = "production")
#Bean(name = "productionLocalEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder.dataSource(productionDataSource()).persistenceUnit("production").packages("org.datalis.plugin.production.entity").build();
}
#Primary
#Bean(name = "productionTransactionManager")
public PlatformTransactionManager productionTransactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Primary
#Bean(name = "productionExceptionTranslation")
public PersistenceExceptionTranslationPostProcessor productionExceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private static class JndiPropertyHolder {
private String jndiName;
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
}
}
I try to use the entity manager this way:
#Service
#Transactional(value = "productionEntityManager")
public class ..... {
#PersistenceContext(unitName = "production")
private EntityManager entityManager;
}
But I get an error during deployment:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
Do you know where my configuration is wrong?
You seem to be missing a bean for EntityManagerFactory. You're requesting it here:
public EntityManager productionEntityManager(EntityManagerFactory emf) {
Try adding
#Primary
#Bean(name = "productionEntityManagerFactory")
public EntityManagerFactory productionEntityManagerFactory() {
return Persistence.createEntityManagerFactory("production");
}
Currently I have to connect two Oracle Datasources in my Spring Boot proyect. I think that I did well the configuration because Spring validated my connection but when I call a service this always response me "Empty". I think is because the TransactionManager don't change.
This is my project structure:
- project
⊢---- config
⊢---- controllers
∟---- models
⊢---- dao
| ⊢---- db1
| ∟---- db2
⊢---- entity
| ⊢---- db1
| ∟---- db2
⊢---- services
⊢---- db1
∟---- db2
This are my entities classes:
package project.models.entity.db1;
//// IMPORTS
#Entity(name = "User")
#Table(name = "T_USER")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String name;
private String surname;
private String username;
private String password;
////// CONSTRUCT
////// GETTERS & SETTERS
////// HASCODE, EQUALS AND TOSTRING
}
package project.models.entity.db2;
//// IMPORTS
#Entity(name = "Shareholder")
#Table(name = "Shareholder")
public class Shareholder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private Integer numberTitles;
////// CONSTRUCT
////// GETTERS & SETTERS
////// HASCODE, EQUALS AND TOSTRING
}
This are my repositories classes:
package project.models.dao.db1;
//// IMPORTS
#PersistenceContext(name = "db1")
#Repository
public interface IUserDao extends JpaRepository<User, Long> {
}
package project.models.dao.db2;
//// IMPORTS
#PersistenceContext(name = "db2")
#Repository
public interface IShareholderDao extends JpaRepository<Shareholder, Integer> {
}
This are my services classes:
package project.models.services.db1.impl;
//// IMPORTS
#Service
public class UserServiceImpl implements IUserService {
#Autowired
private IUserDao userDao;
#Override
#Transactional("transactionManager")
public List<User> findAll() {
return userDao.findAll();
}
#Override
#Transactional("transactionManager")
public User findById(Long id) {
return userDao.findById(id).orElse(null);
}
package project.models.services.db2.impl;
//// IMPORTS
#Service
public class ShareholderServiceImpl implements IShareholderService {
#Autowired
private IShareholderDao shareholderDao;
#Override
#Transactional("db2TransactionManager")
public List<Shareholder> findAll() {
return shareholderDao.findAll();
}
#Override
#Transactional("db2TransactionManager")
public Shareholder findById(Integer id) {
return shareholderDao.findById(id).orElse(null);
}
}
And this are my config classes:
package project.config;
//// IMPORTS
#Configuration
#ConfigurationProperties(prefix = "oracle1")
#EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager", basePackages = {
"project.models.dao.db1" })
#EnableTransactionManagement
#Validated
public class Db1Config {
#NotNull
private String username;
#NotNull
private String password;
#NotNull
private String url;
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws SQLException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "project.models.entity.db1" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(hibernateProperties());
em.setPersistenceUnitName("db1");
return em;
}
#Bean(name = "dataSource")
DataSource dataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setURL(url);
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() throws SQLException {
return new JpaTransactionManager(entityManagerFactory().getObject());
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "validate");
return properties;
}
}
package project.config;
//// IMPORTS
#Configuration
#ConfigurationProperties(prefix = "oracle2")
#EnableJpaRepositories(entityManagerFactoryRef = "db2EntityManagerFactory", transactionManagerRef = "db2TransactionManager", basePackages = {
"project.models.dao.db2" })
#EnableTransactionManagement
#Validated
public class Db2Config {
#NotNull
private String username;
#NotNull
private String password;
#NotNull
private String url;
#Bean(name = "db2EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean db2EntityManagerFactory() throws SQLException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(db2DataSource());
em.setPackagesToScan(new String[] { "project.models.entity.db2" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(hibernateProperties());
em.setPersistenceUnitName("db2");
return em;
}
#Bean(name = "db2DataSource")
DataSource db2DataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setURL(url);
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean(name = "db2TransactionManager")
public PlatformTransactionManager db2TransactionManager() throws SQLException {
return new JpaTransactionManager(db2EntityManagerFactory().getObject());
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "validate");
return properties;
}
}
And my main application:
package project;
//// IMPORTS
#SpringBootApplication
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class })
#EnableCaching
public class ProjectApplication {
#Autowired
private IUserService userService;
#Autowired
private IShareholderService shareholderService;
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
#PostConstruct
void init() {
List<User> user = userService.findAll();
List<Shareholder> shareholder = shareholderService.findAll();
System.out.println();
System.out.println(user);
System.out.println(shareholder);
System.out.println();
}
}
And always response me:
[User [id=39, name=Jack, surname=Sparrow, ...], [...], ...]
[]
What is the error? Because I don't see it.
Thank you very much
In Db2Config class, package being scanned is different than Db1Config.
Db1Config:
em.setPackagesToScan(new String[] { "project.models.entity.db1" });
Db2Config
em.setPackagesToScan(new String[] { "project.models.dao.db2" });
I'm not sure why Spring boot doesn't recognize my second data source which I think is configured right.
I'm keep getting this message: ...Error creating bean with name 'leadRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ref.api.test.lead.model.LeadEntity
I setted the right path for.packages("com.ref.api.test.lead.model") but for some reason spring-boot don't check my entity there.
PrimaryDsConfig
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.ref.api.repository" }
)
public class PrimaryDsConfig {
#Primary
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("dataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.ref.api.model")
.persistenceUnit("foo")
.build();
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
AdditionDsConfig
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "barEntityManagerFactory",
transactionManagerRef = "barTransactionManager",
basePackages = { "com.ref.api.test.lead.repository" }
)
public class AdditionDsConfig {
#Bean(name = "barDataSource")
#ConfigurationProperties(prefix = "addition.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "barEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean
barEntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("barDataSource") DataSource dataSource
) {
return
builder
.dataSource(dataSource)
.packages("com.ref.api.test.lead.model")
.persistenceUnit("bar")
.build();
}
#Bean(name = "barTransactionManager")
public PlatformTransactionManager barTransactionManager(
#Qualifier("barEntityManagerFactory") EntityManagerFactory
barEntityManagerFactory
) {
return new JpaTransactionManager(barEntityManagerFactory);
}
application.yml
spring:
datasource:
jdbc-url: jdbc:postgresql://blabla..
username: bla
password: bla
addition:
datasource:
jdbc-url: jdbc:postgresql://blabla2..
username: bla2
password: bla2
LeadEntity
package com.ref.api.test.lead.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "lead")
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#SequenceGenerator(name = "lead_id_seq",
sequenceName = "lead_id_seq",
allocationSize = 1)
public class LeadEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "lead_id_seq")
private Long lead_id;
private String place_id;
private String name;
private String formatted_address;
private String country;
private String state;
private String city;
private String postal_code;
private String formatted_phone_number;
private String international_phone_number;
private String website;
private String vicinity;
private String rating;
private String price_level;
private String lat;
private String lng;
private String types;
private String place_url;
private String utc_offset;
private String opening_hours;
private String email;
private String logo;
}
LeadRepository
package com.ref.api.test.lead.repository;
import com.ref.api.test.lead.model.LeadEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LeadRepository extends JpaRepository<LeadEntity, Long> {
}
ApiApplication
#SpringBootApplication
#EnableJpaRepositories(repositoryFactoryBeanClass = EntityGraphJpaRepositoryFactoryBean.class)
#EnableCaching
public class ApiApplication {
I figure out why spring-boot didn't detect my second datasource.
Beacuse I had #EnableJpaRepositories on my public class ApiApplication so it was confused.
When I moved repositoryFactoryBeanClass = EntityGraphJpaRepositoryFactoryBean.class to my PrimaryDsConfig everything starting working.
So just pay attention how many #EnableJpaRepositories do you have.
There are two data source configuration classes:
#Configuration
#EnableJpaRepositories(
basePackages = {"com.proj.killbill.repository.kb", "com.proj.service.base.repository"},
entityManagerFactoryRef = "kbEntityManagerFactory",
transactionManagerRef = "kbTransactionManager")
#EnableJpaAuditing
#Profile({"dev", "prod"})
public class PersistenceKbConfig {
#Value("${db.user:default}")
private String user;
#Value("${db.password:default}")
private String password;
#Value("${db.url:default}")
private String jdbcUrl;
#Value("${app.kb.ds.jndi.name}")
private String kbDsJndiName;
#Bean(name = "kbDataSource")
#Profile("dev")
public DataSource devKbDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
#Bean(name = "kbDataSource")
#Profile("prod")
public DataSource prodKbDataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
return dsLookup.getDataSource(kbDsJndiName);
}
#SuppressWarnings("Duplicates")
#Bean(name = "kbEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
#Qualifier("kbDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.proj.service.base.domain");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
return properties;
}
#Bean(name = "kbTransactionManager")
public PlatformTransactionManager kbTransactionManager(
#Qualifier("kbEntityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
#Configuration
#EnableJpaRepositories(
basePackages = {"com.proj.killbill.repository.cm", "com.proj.service.base.repository"},
entityManagerFactoryRef = "cmEntityManagerFactory",
transactionManagerRef = "cmTransactionManager")
#EnableJpaAuditing
#Profile({"dev", "prod"})
public class PersistenceCmConfig {
#Value("${cm.db.user:default}")
private String user;
#Value("${cm.db.password:default}")
private String password;
#Value("${cm.db.url:default}")
private String jdbcUrl;
#Value("${app.cm.ds.jdni.name}")
private String cmJndiName;
private static final Logger LOGGER = LogManager.getLogger(PersistenceCmConfig.class);
#Bean(name = "cmDataSource")
#Profile("dev")
public DataSource devCmDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(user);
dataSource.setPassword(password);
LOGGER.debug("CM JDBC URL USER/PASSWORD" + jdbcUrl + " " + user + "/" + password);
return dataSource;
}
#Bean(name = "cmDataSource")
#Profile("prod")
public DataSource prodCmDataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
return dsLookup.getDataSource(cmJndiName);
}
#SuppressWarnings("Duplicates")
#Bean(name = "cmEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean cmEntityManagerFactory(
#Qualifier("cmDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.proj.service.base.domain");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
return properties;
}
#Bean(name = "cmTransactionManager")
public PlatformTransactionManager cmTransactionManager(
#Qualifier("cmEntityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
Entity managers use #Qualifier annotations to inject appropriate data sources. But when I start the app I get the exception:
==========
Parameter 0 of method cmEntityManagerFactory in com.proj.killbill.config.PersistenceCmConfig required a single bean, but 2 were found:
- cmDataSource: defined by method 'devCmDataSource' in class path resource [com/proj/killbill/config/PersistenceCmConfig.class]
- kbDataSource: defined by method 'devKbDataSource' in class path resource [com/proj/killbill/config/PersistenceKbConfig.class]
Action:
Consider marking one of the beans as #Primary, updating the consumer to accept multiple beans, or using #Qualifier to identify the bean that should be consumed
============
#Qualifier("cmDataSource") is just ignored for unknown reason. Why can it be possible?
I have got No transactional EntityManager available exception when I tried to persist an object.
I have a Spring project with the following configuration class:
#Configuration
#ComponentScan
#EnableTransactionManagement
#EnableJpaRepositories
public class SpringConfiguration {
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean emf(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf =new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
jpaProperties.put("hibernate.show_sql", "true");
emf.setJpaProperties(jpaProperties);
emf.setPackagesToScan(
new String[] {"ds.core.entity"});
emf.setJpaVendorAdapter(
new HibernateJpaVendorAdapter());
return emf;
}
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory emf,DataSource dataSource) {
JpaTransactionManager tm =
new JpaTransactionManager();
tm.setEntityManagerFactory(emf);
tm.setDataSource(dataSource);
return tm;
}
And an entity class:
#Entity
public class Type {
#Id #GeneratedValue
private Long id;
private String name;
}
and Jpa implementation class :
#Repository
public class JpaTypeRepo implements TypeRepo {
#PersistenceContext
private EntityManager em;
#Override
public Type insertRecord(Type data) {
em.persist(data);
return data;
}
}
And finally a Service Class with Init():
#Transactional
#Service
public class InitDbService {
#Autowired
private TypeRepo typeRepo;
#PostConstruct
public void init() {
Type type=new Type();
type.setName("newName");
typeRepo.insertRecord(type);
}}
just add #Transactional annotation to the class :JpaTypeRepo
as following:
#Transactional
#Repository
public class JpaTypeRepo implements TypeRepo {
#PersistenceContext
private EntityManager em;
#Override
public Type insertRecord(Type data) {
em.persist(data);
return data;
}
}