I have a simple code. I added some players to database and here I want to set nick in first player:
private void mod() {
Player p = playersService.loadById(1L);
p.setNick("OtherNick");
}
It gives: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
PlayersService.load():
@Transactional
public Player loadById(Long id) {
return playersDao.load(id);
}
PlayersDao.load() - extended from AbstractDao:
@SuppressWarnings("unchecked")
public T load(Serializable id) {
return (T) currentSession().load(getDomainClass(), id);
}
I have here one more question: @Transactional should be in DAO layer or Service layer?
Hibernate Config:
// package declaration and import statements
@Configuration
@ComponentScan(basePackages = { "eniupage" }, excludeFilters = {
@Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
@EnableTransactionManagement
public class RootConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName( "com.mysql.jdbc.Driver" );
dataSource.setUrl( "jdbc:mysql://localhost:3306/eniupage" );
dataSource.setUsername( "eniupage" );
dataSource.setPassword( "qwer1234" );
return dataSource;
}
@Autowired
@Bean
public LocalSessionFactoryBean sessionFactory( DataSource dataSource ) {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
sfb.setDataSource( dataSource );
sfb.setPackagesToScan( new String[] { "eniupage.domain"} );
Properties props = new Properties();
props.setProperty( "hibernate.dialect", "org.hibernate.dialect.MySQLDialect" );
props.setProperty( "hibernate.hbm2ddl.auto", "create-drop" );
props.setProperty( "hibernate.show_sql", "true" );
sfb.setHibernateProperties( props );
return sfb;
}
@Bean
public BeanPostProcessor persistenceTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(
sessionFactory);
return transactionManager;
}
}