F
F
fife2021-06-24 20:57:45
Java
fife, 2021-06-24 20:57:45

Where to create sessionFactory in Spring project?

Good evening, I'm just starting to work with hibernate, before that I worked with spring data.

Task: You need to create a Note table using hibernate JPA mapping

In a normal hibernate project, you can simply write

public class Main {
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    }
}


And then a new table will appear in the database.

I'm a little dumb, how to do this in a Spring project where there is no main`a, so that when the project starts, a table is also created in the database?

The entity for which you want to create a table.

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "notes")
public class Note {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    private String text;

    private Date date;

    public Note() {
    }

    public Note(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

hibernateUtil
public class  HibernateUtil {
    private static SessionFactory sessionFactory = null;

    static {
        Configuration cfg = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties());

        sessionFactory = cfg.buildSessionFactory(builder.build());
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}


hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name = "connection.driver_class">org.postgresql.Driver</property>
        <property name = "connection.url">jdbc:postgresql://localhost:5432/note</property>
        <property name = "connection.username">postgres</property>
        <property name = "connection.password">admin</property>
        <property name = "show_sql">true</property>
        <property name = "hibernate.hbm2ddl.auto">update</property>

        <mapping class="com.notes.entity.Note" />
    </session-factory>
</hibernate-configuration>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-06-24
@fife

Good afternoon.
What exactly is the problem?
It looks like you have hibernate.cfg.xml and you also have HibernateUtil.
You can slightly tweak this class to this option:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {

  final static StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
      .configure()
      .build();

  private static final SessionFactory sessionFactory;

  static {
    try {
      sessionFactory = new MetadataSources(registry).buildMetadata()
          .buildSessionFactory();
    } catch (Throwable ex) {
      throw new ExceptionInInitializerError(ex);
    }
  }

  public static Session getSession()
      throws HibernateException {
    Session session = null;
    try {
      session = sessionFactory.getCurrentSession();
    } catch (org.hibernate.HibernateException he) {
      session = sessionFactory.openSession();
    }
    return session;
  }

}

Next, using the getSession() method, you get the session and do what you need.
For example,
Session session = HibernateUtil.getSession();
      session.beginTransaction();
      note.setTitle("Example");
      session.merge(note);
      session.getTransaction().commit();
      session.close();

how to do this in a Spring project where there is no main

Why is there no main method in the Spring project?
Here is a Spring Framework tutorial where the main method is listed - https://www.youtube.com/watch?v=nLCYk1ySY_U

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question