Hibernate没有在表中保存数据,但是重新调用session.get()

时间:2014-03-11 13:16:04

标签: hibernate

我正在尝试将对象保存到数据库,但它没有保存到数据库中。

UserDetails.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {

    @Id @GeneratedValue()
    @Column(name="USER_ID")
    private int userId;

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

    //...getter and setters

}

App.java

public class App {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserName("abc");

        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session session = factory.openSession();

        Object o = session.save(user);
        System.out.println("User saved with id - " +o);
        System.out.println("HashCode of session 1st "+session.hashCode());
        session.close();

        session = factory.openSession();
        System.out.println("HashCode of session 2nd "+session.hashCode());

        UserDetails user1 =(UserDetails)session.get(UserDetails.class,Integer.valueOf(o.toString()));
        System.out.println(user1.getUserName());

        session.close();



    }
}

日志:

Hibernate: insert into USER_DETAILS (USER_ID, USER_NAME) values (default, ?)
Hibernate: values identity_val_local()
User saved with id - 1
HashCode of session 1st 9299042
HashCode of session 2nd 12206609
Hibernate: select userdetail0_.USER_ID as USER1_0_0_, userdetail0_.USER_NAME as USER2_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.USER_ID=?
abc

我没有使用该事务,我知道如果我将session.save代码放在session.beginTransaction()和session.getTransaction()。commit()中,数据将保存在数据库中。但是,当我在做session.save()时我正在进行会话。我正在进行会话。我如何获取对象?

如果它是第一级缓存然后是怎么...因为我也在关闭会话并打开一个新会话。我也没有配置任何二级缓存。

请提供有价值的意见。

0 个答案:

没有答案