-2

I am getting below error in my application while trying to persist an object into database.

nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.delivery.Message

Entity:

@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter @Setter @ToString
@AllArgsConstructor
public class Message {

    @Id
    @Basic
    @GeneratedValue(generator = "MESSAGE_SEQ", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "MESSAGE_SEQ", sequenceName = "MESSAGE_ID_SEQ")
    @Column(name = "MESSAGE_ID")
    protected long messageId;

    @Column(name = "MESSAGE")
    private String message;

    @Column(name = "STATUS")
    private String status;
}

DAO Layer:

@Transactional
public void saveEntity(@Nullable T entity) {
    if (entity = null) {
        return;
    }

    entityManager.persist(entity);
    entityManager.flush();
    entityManager.detach(entity);
}

Service Layer:

public void saveMessage(HttpEntity<Message> entity) throws Exception{
    try{
        repository.saveEntity(entity);    
    }catch(Exception e){
        throw e;
    }
    
}

Not sure why am getting this error. Error is thrown at persist method. Any reason for this issue?

PDJ
  • 69
  • 8
  • That generally means the ID is populated. When the ID is populated, the assumption is that the database record already exists and then you need to merge the data, not persist it. – Gimby Sep 09 '20 at 09:36
  • 1
    Does this answer your question? [PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate](https://stackoverflow.com/questions/13370221/persistentobjectexception-detached-entity-passed-to-persist-thrown-by-jpa-and-h) – SternK Sep 09 '20 at 10:22

1 Answers1

0

You should check is messageId filled in the received entity. Try this code:

if (entity.getId() == null) {
    entityManager.persist(entity);
} else {
    entityManager.merge(entity);
}

You should use Long type instead of primitive long to allow identificator be null.