Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: get entity by id

Tags:

java

hibernate

I have user entity and trying to get it from base by id. The entity definition is below.

package com.hibernate.logic;

import java.io.Serializable;
import java.util.Random;

import javax.persistence.*;

@Entity
@Table(name="users")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

@Id
@Column(name="user_id")
private Long userId;

@Column(name="middlename")
private String middlename;

@Column(name="name")
private String name;

@Column(name="surname")
private String surname;

@Column(name="pass")
private String pass;

//bi-directional many-to-one association to Role
@ManyToOne
@JoinColumn(name="role_id")
private Role role;

public User() {
    Random random = new Random();
    this.userId = random.nextLong();
    this.name = "";
    this.surname = "";
    this.middlename = "";
}

public Long getUserId() {
    return this.userId;
}

public void setUserId(Long userId) {
    this.userId = userId;
}

public String getMiddlename() {
    return this.middlename;
}

public void setMiddlename(String middlename) {
    this.middlename = middlename;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return this.surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Role getRole() {
    return this.role;
}

public void setRole(Role role) {
    this.role = role;
}

public String getPass() {
    return pass;
}

public void setPass(String pass) {
    this.pass = pass;
}

}

So the method getUserById(Long user_id) doesn't get the information from database, it's just call user constructor. Why is it so?

public User getUserById(Long user_id) {
        Session session = null;
        User user = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  session.load(User.class,
                    user_id);
            Hibernate.initialize(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return user;
    }
like image 904
Anatoly Avatar asked Jun 18 '12 19:06

Anatoly


People also ask

How does Hibernate fetch multiple entities by id?

Load multiple entities by their primary key class ); List<PersonEntity> persons = multiLoadAccess. multiLoad(1L, 2L, 3L); You just need to call the byMultipleIds(Class entityClass) method on the Hibernate Session and provide the class of the entities you want to load as a parameter.

Which two methods are used for retrieval by identifier in Hibernate?

The get() method is very much similar to load() method. The get() methods take an identifier, and either an entity name or a class types.

How can I get single record in Hibernate?

Use the uniqueResult() API method of Criteria to get the single instance that matches the query. Use again getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction .

How can I get multiple records in Hibernate?

Session session = HibernateUtil. getCurrentSession(); If you want to fetch the records from a database table try this simple query: List<Object> slist = session.


3 Answers

use get instead of load

// ...
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  (User) session.get(User.class, user_id);
        } catch (Exception e) {
 // ...
like image 113
Ilya Avatar answered Oct 19 '22 08:10

Ilya


In getUserById you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user. Otherwise Hibernate.initialize(user); is actually Hibernate.initialize(null);

Here's the new getUserById (I haven't tested this ;)):

public User getUserById(Long user_id) {
    Session session = null;
    Object user = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        user = (User)session.load(User.class, user_id);
        Hibernate.initialize(user);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return user;
}
like image 29
Michael Kohler Avatar answered Oct 19 '22 08:10

Michael Kohler


Using EntityManager em;

public User getUserById(Long id) {
     return em.getReference(User.class, id);
}
like image 1
Igor Vuković Avatar answered Oct 19 '22 09:10

Igor Vuković