2

I have successfully set up a DAO by creating and closing hibernate sessions manually. Here for I used a "hibernate.cfg.xml" file and a "HibernateUtil" class.

I now want to use spring's autowire ability to automatically create and close hibernate sessions.

What I have already done:

(1) Move hibernate.cfg.xml content over to application.properties

spring.datasource.url="dummy"
spring.datasource.username="dummy"
spring.datasource.password="dummy"
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jooq.sql-dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

(2) DOA class

@Repository
public class CarpoolDOA implements ICarpoolDoa {

    @Autowired
    SessionFactory sessionFactory;

    public List<User> getPassengersTour(int tourId) {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Tour tour = (Tour) session.get(Tour.class, tourId);
        return tour.getPassengers();
    }      
}

(3) This bean is in place

@Autowired
@Bean(name="sessionFactory")
public SessionFactory sessionFactory(HibernateEntityManagerFactory factory) {
   return factory.getSessionFactory();
}

This code actually runs, but it is not using the configuration provided in application.properties. I guess it is loading standard hibernate configurations as seen on startup.

Output on startup:

 HHH000412: Hibernate Core {4.3.11.Final}
 HHH000206: hibernate.properties not found
 HHH000021: Bytecode provider name : javassist
 HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
 HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
 HHH000397: Using ASTQueryTranslatorFactory
 HHH000227: Running hbm2ddl schema export

How can I tell Spring Boot to use my configuration?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
G-J
  • 401
  • 7
  • 17
  • 1
    Do you have spring-boot-starter-data-jpa in your pom? – jny Dec 21 '15 at 22:05
  • I have switched 'SessionFactory' for 'HibernateJpaSessionFactoryBean' and added 'spring-boot-starter-data-jpa'. Thanks! Your suggestion solved it! Follow up question: Is this the right way to handle Hibernate in spring (boot)? While looking for a solution I have found a thousand different ways to implement both. – G-J Dec 21 '15 at 22:17
  • Generally speaking, it's preferable to use standard JPA APIs rather than Hibernate's proprietary ones. – chrylis -cautiouslyoptimistic- Dec 22 '15 at 06:10
  • You should consider JPA combined wirh spring data for an efficient implementation – Guy Bouallet Dec 22 '15 at 08:26
  • And why should `spring.jooq` properties work for `spring.jpa`? Next to that if you don't need access to specific hibernate features you are probably better of using plain JPA instead. – M. Deinum Dec 23 '15 at 06:24
  • see this http://stackoverflow.com/a/33881946/455654 – Aalkhodiry May 15 '16 at 13:22

0 Answers0