简体   繁体   中英

hibernate persist not working

I have a simple AppUser entity class and table in db APP_USERS . when i do a addAppUser from DAO class, I get below exception:

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.spring.model.AppUser

@Override
public void addAppUser(AppUser p) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(p);
    logger.info("AppUser saved successfully, AppUser Details="+p);
}

Not sure how to resolve it. Same code works fine for persisting a different class's object. Did some research but could not find anything that could help.

The problem is that your AppUser comes from the outside, so it is not managed by hibernate. Call merge to reattach your DAO, ie make hibernate handle it again:

session.merge(p);

If you still run into an exception, you can try to see if the object is already in the session first, and then call update(obj) if it is, otherwise call merge(obj) .

For example:

if(session.contains(obj)) session.update(obj);
else session.merge(obj);

i had issue because i had the below naive code .. didn't notice it.

    @Id
    @Column(name = "enterid")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String enterid;

It was not able to autogenerate the enterid which is 'String' and it turned to null. I noticed that during debugging.

Hibernate: insert into app_users (enterid, lead, enable, password, approval, role, teamname) values (null, ?, ?, ?, ?, ?, ?)

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