Java hibernate session.get inside constructor

far2005 :

I have just begun using hibernate in my project and i'm struggling to understand hibernate. This is my model:

package tech.simorgh.syam.model;

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

import javax.persistence.*;

@Entity
@Table(name = "tbl_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int user_id;

    @Column(nullable = false)
    private String firstName, lastName, fatherName, password, email;


    public int getUser_id() {
        return user_id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getFatherName() {
        return fatherName;
    }

    public String getPassword() {
        return password;
    }

    public String getEmail() {
        return email;
    }
}

I am looking for a way to initilize my class like this:

 User user = new User(1);
 System.out.printf(user.getFirstName());

I am using spring boot and hibernate to build this project

Code_Mode :

You are not required to use constructor to fetch the data from database. You can directly call session.get to fetch the record.

User user = (User) session.get(User.class, 1);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98543&siteId=1