Source code for 'No Hibernate Session bound to thread'

This commit is contained in:
Julius Krah
2016-07-28 16:59:19 +00:00
parent b53e46246b
commit b18e9cf019
10 changed files with 273 additions and 137 deletions
@@ -0,0 +1,23 @@
package org.baeldung.session.exception;
import org.baeldung.boot.model.Foo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
@EntityScan(basePackageClasses = Foo.class)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
System.setProperty("spring.config.name", "exception");
System.setProperty("spring.profiles.active", "exception");
SpringApplication.run(Application.class, args);
}
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
}
@@ -0,0 +1,10 @@
package org.baeldung.session.exception.repository;
import org.baeldung.boot.model.Foo;
public interface FooRepository {
public void save(Foo foo);
public Foo get(Integer id);
}
@@ -0,0 +1,25 @@
package org.baeldung.session.exception.repository;
import org.baeldung.boot.model.Foo;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;
@Profile("exception")
@Repository
public class FooRepositoryImpl implements FooRepository {
@Autowired
private SessionFactory sessionFactory;
@Override
public void save(Foo foo) {
sessionFactory.getCurrentSession().saveOrUpdate(foo);
}
@Override
public Foo get(Integer id) {
return (Foo) sessionFactory.getCurrentSession().get(Foo.class, id);
}
}