简体   繁体   中英

Hibernate : object references an unsaved transient instance - save the transient instance before flushing

I receive following error when i try to get List using hibernate + postgresql

MyObject:

@Entity
@Table(name = "my_objects", schema = "public")
public class MyObject implements java.io.Serializable {

private static final long serialVersionUID = 1L;
@Id
@Column(name = "my_object_id", unique = true, nullable = false)
@GeneratedValue
private long myObjectId;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "owner_id")
private User user;

@Column(name = "scheme_zone_name", length = 150)
private String schemeZoneName;

@Temporal(TemporalType.DATE)
@Column(name = "create_dt", length = 13)
private Date createDt;

@Column(name = "comment", length = 250)
private String comment;


public MyObject() {
}

public MyObject(long myObjectId) {
    this.myObjectId = myObjectId;
}

public MyObject(long myObjectId, User user,  String myObjectName, Date createDt, String) {
    this.schemeZoneId = schemeZoneId;
    this.user = user;
    this.myObjectName = myObjectName;
    this.createDt = createDt;
    this.comment = comment;
} ....getters/setters .....}

User :

@Entity
@Table(name = "dp_users", schema = "public")
public class User implements java.io.Serializable {

private static final long serialVersionUID = 1L;
@Id
@Column(name = "user_id", unique = true, nullable = false, precision = 5, scale = 0)
@GeneratedValue
private int userId;

@Column(name = "user_login", nullable = false, length = 25)
private String userLogin;

@Column(name = "user_password", nullable = false, length = 25)
private String userPassword;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private Set<MyObject> myObjects = new HashSet(0);

public User() {
}

public User(int userId, String userLogin, String userPassword) {
    this.userId = userId;
    this.userLogin = userLogin;
    this.userPassword = userPassword;
}

public User(int userId, String userLogin, String userPassword, Set<MyObject> myObjects) {
    this.userId = userId;
    this.userLogin = userLogin;
    this.userPassword = userPassword;
    this.myObjects = myObjects;
} ....getters/setters .....}

At first I get User and save it in User object:

public User login(String login, String password) {
    Session session = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        return (User) session.createCriteria(User.class)
                .add(Restrictions.eq("userLogin", login).ignoreCase())
                .add(Restrictions.eq("userPassword", password)).uniqueResult();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return null;
}

Then, when I try to get a List of MyObject by User :

public List<MyObject> getMyObjects(User user) throws SQLException {
    List<MyObject> o = null;
    Session session = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        o = session.createCriteria(MyObject.class)
                .add(Restrictions.eq("user", user))
                .addOrder(Order.asc("myObjectName"))
                .list();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return o;
}

I receive

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: cc.testProject.common.User

What have I done wrong?

You should use the same session to retrieve all entities. the session scope must match your unit of work, don't instantiate it for each operation.

See Struggling to understand EntityManager proper use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM