【问题标题】:Detached entity passed to persist: JPA Error传递给持久化的分离实体:JPA 错误
【发布时间】:2020-12-27 17:08:46
【问题描述】:

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

嵌套异常是 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


【解决方案1】:

你应该检查是否messageId填写了接收的实体。试试这个代码:

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

您应该使用Long 类型而不是原始long 来允许标识符为空。

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 2017-10-21
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多