Spring + Hibernate : No Session Found For Current Thread - java

I'm having difficulties solving this problem:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:993)
at com.veram.dao.UsuariosDaoImp.findByUserName(UsuariosDaoImp.java:23)
at com.veram.servicos.ServicosUsuario.loadUserByUsername(ServicosUsuario.java:31)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:101)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
Classes:
AppConfig
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.ver.*"})
#Import({ SecurityConfig.class, DataBaseConfig.class })
public class AppConfig extends WebMvcConfigurerAdapter
{
//Adiciona a pasta resources ao dispatcher do MVC
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
//Localização das views da minha aplicação
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
DataBaseConfig:
#Configuration
#Import({ SecurityConfig.class })
public class DataBaseConfig
{
#Bean
public SessionFactory sessionFactory()
{
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.ver.entid").addProperties(getHibernateProperties());
return builder.buildSessionFactory();
}
private Properties getHibernateProperties()
{
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/veram_prod");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
#Bean
public HibernateTransactionManager txManager()
{
return new HibernateTransactionManager(sessionFactory());
}
}
UserServices:
#Service("userDetailsService")
public class ServicosUsuario implements UserDetailsService
{
#Autowired
private UsuariosDao userDao;
#Transactional(readOnly=true)
#Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException
{
com.veram.entidades.Usuarios user = userDao.findByUserName(username);
}
}
UserDaoImp
#Repository
public class UsuariosDaoImp implements UsuariosDao
{
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public Usuarios findByUserName(String username)
{
List<Usuarios> users = new ArrayList<Usuarios>();
users = sessionFactory.getCurrentSession()
.createQuery("from usuarios where usuario=?")
.setParameter(0, username)
.list();
if (users.size() > 0)
{
return users.get(0);
}
else
{
return null;
}
}
}
I'm trying to understand the configuration for Spring and Hibernate. Every time I try to access the current session, I get a no session found for current thread error in my console (doesn't stop the app).
If anyone can help, I appreciate!

Try adding #EnableTransactionManagement to DataBaseConfig

Related

hibernate5 + spring boot connect multiple databases

I want to use hibernate to connect two different databases and use different sessionfactory to operate the data
In the example below , Another datasource and LocalSessionFactoryBean will be added in the #Configuration class , but how do I give these two sessionFactory specific names?
Reference:
https://www.baeldung.com/hibernate-5-spring
#Configuration
#EnableTransactionManagement
public class HibernateConf {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(
{"com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return hibernateProperties;
}
}
Want to reach the effect:
#Service
#Transactional
public class TestRepositoryImpl implements TestRepository{
#Qualifier("connectionA")
#Autowired
private SessionFactory sessionFactory;
#Qualifier("connectionB")
#Autowired
private SessionFactory sessionFactory;
...
...
}
Another project example:
#Configuration
public class DataSourceConfig {
#Primary
#Bean(name = "test1DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource test1DataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "test2DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource test2DataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Autowired
#Bean(name = "test1Connection")
public NamedParameterJdbcTemplate test1JdbcTemplate(#Qualifier("test1DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Autowired
#Bean(name ="test2Connection")
public NamedParameterJdbcTemplate test2JdbcTemplate(#Qualifier("test2DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
}
Any help is greatly appreciated!
If you want to achieve hibernate with two Database: use session factory like below.
But i recommend use Spring Data JPA it will give more specification and easier to understand.
public class Transfer {
public static void main(String[] args) {
// get the SessionFacotry
SessionFactory connectionAFactory = HibernateConf.getSessionFactory();
SessionFactory connectionBFactory= DataSourceConfig.getSessionFactory();
// get The Session
Session connectionASes = HibernateConf.getSession();
Session connectionBSes = DataSourceConfig.getSession();
For this you can configure your data connection beans like this:
#Configuration
public class DataSourceConfig {
#Primary
#Bean(name = "test1DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource test1DataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "test2DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource test2DataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Autowired
#Bean(name = "test1Connection")
public NamedParameterJdbcTemplate test1JdbcTemplate(#Qualifier("test1DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Autowired
#Bean(name ="test2Connection")
public NamedParameterJdbcTemplate test2JdbcTemplate(#Qualifier("test2DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
}
After that you can autowire them separately by using #Qualifier in following way in your service class:
#Service
#Transactional
public class TestRepositoryImpl implements TestRepository{
#Qualifier("test1Connection")
#Autowired
private SessionFactory sessionFactory1;
#Qualifier("test2Connection")
#Autowired
private SessionFactory sessionFactory2;
...
...
}

Can't map class to Hibernate without xml with ".setAnnotatedClasses()" Getting "2QuerySyntaxException: FileEntity is not mapped" error

Hi everyone.
I am trying to map class (FileEntity) to Hibernate using .setAnnotatedClasses() or .setPackagesToScan() methods. But I get the same error over and over again.
org.hibernate.hql.internal.ast.QuerySyntaxException: FileEntity is not mapped
When I mapped the class with .xml all worked fine.
Please tell me, where is my mistake?
ApplicationContextConfig.java
#Configuration
#ComponentScan("com.group.appName")
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class ApplicationContextConfig {
#Autowired
Environment environment;
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
return new InternalResourceViewResolver();
}
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(environment.getProperty("spring.datasource.url"));
dataSource.setUsername(environment.getProperty("spring.datasource.username"));
dataSource.setPassword(environment.getProperty("spring.datasource.password"));
return dataSource;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(#Qualifier("dataSource") DataSource dataSource) throws Exception {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getProperty("spring.jpa.properties.hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
properties.put("current_session_context_class", environment.getProperty("spring.jpa.properties.hibernate.current_session_context_class"));
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();
factoryBean.setPackagesToScan("com.group.appName.model");
// or another method
factoryBean.setAnnotatedClasses(FileEntity.class);
return factoryBean.getObject();
}
#Autowired
#Bean(name = "transactionManager" )
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Bean(name = "multipartResolver")
public CommonsMultipartResolver getCommonsMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(20971520); // 20MB
multipartResolver.setMaxInMemorySize(1048576); // 1MB
return multipartResolver;
}
}
FileEntity.java
#Entity
#Table(name ="files_upload")
public class FileEntity {
private String fileName;
private Byte[] fileData;
#Id
#Column(name = "file_name")
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
#Column(name = "file_data")
public Byte [] getFileData() {
return fileData;
}
public void setFileData(Byte [] fileData) {
this.fileData = fileData;
}
}
application.properties
server.port=9090
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/filedb?serverTimezone=Europe/Moscow
spring.datasource.username=root
spring.datasource.password=241299
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Ok. I fixed it.
The point is that in method getSessionFactory after creating an object of class LocalSessionFactoryBean the first line should be
factoryBean.setAnnotatedClasses(FileEntity.class);
So the correct creating an object of LocalSessionFactoryBean class is:
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setAnnotatedClasses(FileEntity.class); - first line.
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();

Hibernate sessionFactory bean throwing java.lang.NullPointerException

I am migrating jdbc to hibernate and i have palced below hibernate configuration in my application.
public class HibernateConfiguration {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.cm.models" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(jdbcurl);
dataSource.setUsername(userName);
dataSource.setPassword(password);
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", true);
properties.put("hibernate.format_sql", true);
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
my application interacting fine with database at application startup creating hibernate session successfully through session factory giving output also.
**#Autowired
private SessionFactory sessionFactory;**
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
but after application startup when i hitting DAO by controller then session factory bean getting Null reference and throwing NullPointerException due to which unable to create or open hibernate session , i tried to find out solution but that's not working please let me know why above SessionFactory bean having nullPointer due to which issue created.
Just to test my DAO logic I am using this controller and This controller hitting to DAO where sessionFacory bean is null.
#RestController
#RequestMapping("/Emp")
public class myController {
#RequestMapping(value = "/findByChannelManager", method = RequestMethod.GET)
public void findemp() {
HotelDaoImpl hotelDaoImpl=new HotelDaoImpl();
List <HotelEntity> list = new ArrayList<>();
list = hotelDaoImpl.findByChannelManager (EnumCM.AR);
for (HotelEntity pro : list) {
System.out.println(pro);
}
}
}
#Repository
#Transactional
public class HotelDaoImpl extends AbstractDao implements IHotelDao {
#SuppressWarnings({ "unchecked", "unused" })
#Override
public List<HotelEntity> findByChannelManager(EnumCM cm) {
List<HotelEntity> list = null;
try {
Session s = getSession();
Criteria criteria=s.createCriteria(Hotel.class);
criteria.add(Restrictions.eq("channelManager", "cm.name()"));
list = criteria.list();
}catch(Exception e) {
LOGGER.debug("error " +e.getMessage());
e.printStackTrace();
}
return list;
}
public abstract class AbstractDao {
#Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
}
You cant access dao from your controller. You can access dao from service so add service class. Try this code
#RestController
#RequestMapping("/Emp")
public class myController {
#Autowired
HotelService service;
#RequestMapping(value = "/findByChannelManager", method = RequestMethod.GET)
public void findemp() {
List <HotelEntity> list = new ArrayList<>();
list = service.findByChannelManager (EnumCM.AR);
for (HotelEntity pro : list) {
System.out.println(pro);
}
}
}
#Service
#Transactional
public class HotelService {
#Autowired
private HotelDao dao;
public List<HotelEntity> findByChannelManager(EnumCM cm) {
return dao.findByChannelManager(EnumCM cm);
}
}
#Repository
public class HotelDaoImpl extends AbstractDao implements IHotelDao {
#SuppressWarnings({ "unchecked", "unused" })
#Override
public List<HotelEntity> findByChannelManager(EnumCM cm) {
List<HotelEntity> list = null;
try {
Session s = getSession();
Criteria criteria=s.createCriteria(Hotel.class);
criteria.add(Restrictions.eq("channelManager", "cm.name()"));
list = criteria.list();
}catch(Exception e) {
LOGGER.debug("error " +e.getMessage());
e.printStackTrace();
}
return list;
}
public abstract class AbstractDao {
#Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
}

Spring Java Config. Transaction problems

I have a spring application with java config:
#Controller
#RequestMapping("/")
public class MainController {
#Inject
#Named("dbDaoService")
IDaoService dbDaoService;
#RequestMapping(value="/saveNoteAsync", method = RequestMethod.POST)
public #ResponseBody String saveNoteAsync(#RequestBody CreateRequest createRequest, HttpServletRequest request) {
Notes newNote = new Notes(
createRequest.getTitle(),
createRequest.getNote(),
tagService.getTagMask(createRequest.getTags())
);
Long newId = dbDaoService.createNotes(newNote);
return ""+newId;
}
}
DBService:
#Service("dbDaoService")
public class DBDaoService implements IDaoService {
#PersistenceContext(unitName = "MyEntityManager")
private EntityManager entityManager;
private List<Tags> tags = null;
#Override
#Transactional
public Long createNotes(Notes data) {
entityManager.persist(data);
return data.getId();
}
}
Configuration class
#Configuration
#EnableWebMvc
#ComponentScan("ru.mypackage")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/views/**").addResourceLocations("/views/");
}
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Bean
public BasicDataSource getBasicDataSource(){
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/test");
bds.setUsername("root");
bds.setPassword("root");
return bds;
}
#Bean
public HibernateJpaVendorAdapter getHibernateJpaVendorAdapter(){
HibernateJpaVendorAdapter hjva = new HibernateJpaVendorAdapter();
hjva.setShowSql(true);
hjva.setGenerateDdl(true);
hjva.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
return hjva;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("MyEntityManager");
em.setDataSource(getBasicDataSource());
em.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
em.setPackagesToScan("ru.eastwind.persistance");
return em;
}
#Bean
public HibernateJpaDialect getHibernateJpaDialect(){
return new HibernateJpaDialect();
}
#Bean
public JpaTransactionManager getJpaTransactionManager(){
JpaTransactionManager jtm = new JpaTransactionManager();
jtm.setEntityManagerFactory(getEntityManagerFactory().getObject());
jtm.setJpaDialect(getHibernateJpaDialect());
return jtm;
}
}
In line entityManager.persist(data); I get the error:
javax.persistence.TransactionRequiredException: No transactional EntityManager available
But all select queries are woking correct! Please, help.
Use #EnableTransactionManagement on #Configuration class
#Configuration
#EnableWebMvc
#ComponentScan("ru.mypackage")
#EnableTransactionManagement
public class WebConfig extends WebMvcConfigurerAdapter {
// ... Your code
}
See Also : http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html

HibernateException: createQuery is not valid without active transaction

The programmatic configuration seems in place but for some reason the application throws exception:
org.springframework.orm.jpa.JpaSystemException: createQuery is not valid without active transaction; nested exception is org.hibernate.HibernateException: createQuery is not valid without active transaction
Code:
#Repository
public class FilmDAOImpl implements FilmDAO {
#Autowired
private HibernateUtil hibernateUtil;
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Film> findFilms(int actorId, int categoryId, int languageId, int releaseYear) {
Query searchQuery = sessionFactory.getCurrentSession().createQuery("from Film " +
"join Actor " +
"join Category " +
"where Category.categoryId=:categoryId " +
"and Film.language.id=:languageId " +
"and Film.releaseYear=:releaseYear " +
"and Actor.actorId=:actorId");
searchQuery.setParameter("categoryId", categoryId);
searchQuery.setParameter("languageId", languageId);
searchQuery.setParameter("releaseYear", releaseYear);
searchQuery.setParameter("actorId", actorId);
return (List<Film>)searchQuery.list();
}
}
Configuration:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories (basePackages = { "com.hibernate.query.performance.persistence" }, transactionManagerRef = "jpaTransactionManager")
#EnableJpaAuditing
#PropertySource({ "classpath:persistence-postgresql.properties" })
#ComponentScan(basePackages = { "com.hibernate.query.performance" })
public class ApplicationConfig {
#Autowired
private Environment env;
public ApplicationConfig() {
super();
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(applicationDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(applicationDataSource());
emf.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaProperties(hibernateProperties());
return emf;
}
#Primary
#Bean
public DriverManagerDataSource applicationDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
#Bean
#Primary
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
transactionManager.setDataSource(applicationDataSource());
return transactionManager;
}
#Bean
public PlatformTransactionManager jpaTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
hibernateProperties.setProperty("hibernate.current_session_context_class", "managed");
hibernateProperties.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");
return hibernateProperties;
}
}
UPDATE
#Service
#Transactional
public class FilmServiceImpl implements FilmService {
#Autowired
private FilmDAO filmDAO;
#Override
public int createFilm(Film film) {
return filmDAO.createFilm(film);
}
#Override
public Film updateFilm(Film film) {
return filmDAO.updateFilm(film);
}
#Override
public void deleteFilm(int id) {
filmDAO.deleteFilm(id);
}
#Override
public List<Film> getAllFilms() {
return filmDAO.getAllFilms();
}
#Override
public Film getFilm(int id) {
return filmDAO.getFilm(id);
}
#Override
public List<Film> findFilms(int actorId, int categoryId, int languageId, int releaseYear) {
return filmDAO.findFilms(actorId, categoryId, languageId, releaseYear);
}
}
Try using openSession() as below, Since getCurrentSession() just attaches to the current session:
Query searchQuery = sessionFactory.openSession().createQuery(...
Also, you need to surround code with proper try..catch..finally block and in finally close the session using session.close()

Categories