传递到持久化的分离实体:JPA 错误

问题描述 投票:0回答:2

尝试将对象保存到数据库时,我的应用程序中出现以下错误。

嵌套异常是 org.hibernate.PersistentObjectException:传递给持久化的分离实体:com.delivery.Message

实体:

@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 层:

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

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

服务层:

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

不确定为什么会出现此错误。 persist 方法抛出错误。这个问题有什么原因吗?

java spring hibernate jpa spring-data-jpa
2个回答
0
投票

您应该检查接收到的实体是否填写了

messageId
。试试这个代码:

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

您应该使用

Long
类型而不是原始
long
来允许标识符为空。


0
投票

就我而言,这是因为我有两个不同的

persistentContext
和两个不同的
transactionManager
,并且我忘记在
transactionManager
中添加正确的
@Transactional

© www.soinside.com 2019 - 2024. All rights reserved.