0

I'm following an online tutorial on how to connect a Java class to a my database using hibernate, however I can't find how to create a SessionFactory since I'm not using a hibernate config file, so

SessionFactory factory = new Configuration().configure() 

doesn't work for me. I used spring initializr with Web, JPA, MySQL to create the project, and I've set up my application.properties accordingly (so hibernate IS connected to the database)

I've tried looking at some other answers such as Spring Boot - Handle to Hibernate SessionFactory

However the answers are a bit outdated/unclear, I'm trying to create an object and begin a transaction with it in my session in my main.java and the only problem I have is getting the FactorySession to work.

In the tutorial it shows a simple solution of

SessionFactory factory = new Configuration().configure("hibernate-cfg.xml.).addAnnotatedClass(Student.class).buildSessionFactory();

Session session = factory.getCurrentSession();

this creates a sessionfactory from the configuration file, and creates a session from that, How can I achieve the same?

ivan l
  • 67
  • 1
  • 4

1 Answers1

0

You should use spring data jpa , it will greatly simply your job.When spring boot will see data JPA in ur classpath it will try to automatically auto wire entity manager for u.Of course it would need database bean as well which in you case should be coming from MYSQL datasource bean.You have to define ur entity classes with @Entity annotation and follow the standard convention of JPA bean. Then u have to extend CrudRepository in your dedicated repository

Lets say you have Person entity with Long as ID of the bean then ur person repository would look like below

@Repository

public interface PersonRepository extends CrudRepository < Person , Long> {

}

Then you can inject this repository in ur service classes or if its small project then in controller. Please check out methods in CrudRepository for more information. It has basic methods for save , update ,delete etc for the entity.

Hope that helps.

whysoseriousson
  • 196
  • 2
  • 16