gpt4 book ai didi

java - Hibernate:通过 id 获取实体

转载 作者:IT老高 更新时间:2023-10-28 20:51:32 27 4
gpt4 key购买 nike

我有用户实体并试图通过 id 从 base 获取它。实体定义如下。

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;
}

}

所以 getUserById(Long user_id) 方法没有从数据库中获取信息,它只是调用用户构造函数。为什么会这样?

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;
}

最佳答案

使用 get 而不是 load

// ...
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User) session.get(User.class, user_id);
} catch (Exception e) {
// ...

关于java - Hibernate:通过 id 获取实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089599/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com