【问题标题】:I can't get a row from a database in hibernate with sessionFactory.getCurrentSession().load (...)我无法使用 sessionFactory.getCurrentSession().load (...) 从休眠的数据库中获取一行
【发布时间】:2012-11-27 01:44:42
【问题描述】:

我有一个数据库(在 postgres 中),我正在使用 spring 3 和 hibernate 3,问题是当尝试从数据库中删除或获取一行时,这是我正在使用的类,哦,另一件事查询后,没有任何错误,唯一的就是那个类User是null

@Repository("userDao")
public class UserDao implements IUserDao {

    @Autowired
    private SessionFactory sessionFactory;

    public void SaveUser(User user) {
    sessionFactory.getCurrentSession().save(user);
    }
    @SuppressWarnings("unchecked")
    public List<User> ListUsers() {
        List<User> users = (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
        return users;
    }
    public User GetUserById(Integer id) {               
        User user = (User) sessionFactory.getCurrentSession().load(User.class, id);
        return user;
    }
}

顺便说一句,方法、SaveUser 和 ListUser 工作得非常好。

这是模型类

@Entity
@Table(name = "mrbean")
public class User {

@Id
@GeneratedValue (strategy = GenerationType.AUTO)
@Column (name = "id")
private Integer id;

@NotNull (message = "not null")
@NotEmpty (message = "empty")
@Column (name = "user_name", length = 20, nullable = false, unique = true)
private String userName;

@NotNull 
@NotEmpty (message = "empty password")
@Size (min = 7, max = 20, message = "La contraseña debe tener entre 7 y 20 caracteres")
@Column (name = "password", length = 20, nullable = false)
private String password;

//带有getter和setter

这是休眠时在控制台中显示的内容 用户 user = (User)sessionFactory.getCurrentSession().load(User.class, id) 被执行

Hibernate:从 mrbean user0_ where user0_.id=?中选择 user0_.id 作为 id0_0_,user0_.password 作为 password0_0_,user0_.user_name 作为 user3_0_0_

【问题讨论】:

  • 您是否检查过数据库中有一行带有您要传递给您的方法的标识符?
  • .... 是的,数据库中有一行标识符为“id”。
  • 最好从明显的检查开始 :)
  • 是的,当然,你是对的,但我调试了很多,一切看起来都很好。你知道另一种从数据库中获取一行的方法吗??
  • 请贴出User.class的源代码,它的映射(如果有单独的)和当你调用getCurrentSession().load()时hibernate使用的查询文本。

标签: spring hibernate


【解决方案1】:

我会使用“get”而不是“load”,因为 load() 创建了 User 的代理(请参阅 Hibernate ref doc) 所以我会尝试: User user = (User) sessionFactory.getCurrentSession().get(User.class, id);

【讨论】:

  • 非常感谢,它现在可以工作了,我可以从数据库中获得使用,但是当我执行 getCurrentSession().delete(user) 时不起作用。仅适用于 HQL,...mmm 那些 getCurrentSession() 方法,我认为最好不要使用,您觉得如何,有什么建议吗???或者我开始学习 HQL。感谢大家的 cmets 真的很有帮助
  • 只需给我们您的删除代码,我会尽力帮助您。您的 getCurrentSession() 没有任何问题。大多数情况下,您会将其分解为私有方法,例如: private Session getSession() { return sessionFactory.getCurrentSession(); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2011-09-17
  • 2016-04-10
  • 1970-01-01
  • 2016-07-24
相关资源
最近更新 更多