1. 问题描述
在做收藏功能时,出现嵌套异常报错
服务端报错日志如下
2021-04-20 20:58:10.607 ERROR 10200 --- [io-8088-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.cwq.bnsp_behind.entity.Collect; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.cwq.bnsp_behind.entity.Collect] with root cause
前端使用VUE+axios库,代码如下
addCollect(){
var _this=this;
this.collect.collectUserId=sessionStorage.getItem("userId");
this.collect.collectArticleId=this.article.articleId;
this.collect.collectState=1;
// alert(this.collect.collectUserId);
this.$axios.put("http://localhost:8088/Collects/addCollect",this.collect)
.then(function (){
_this.$message({
message: '收藏成功',
type: 'success'
});
})
}
2. 解决分析
实体类中有两个字段自动创建。collectId和collectTime
package com.cwq.bnsp_behind.entity;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.util.Date;
@Data
@Entity
//自动创建时间
@EntityListeners(AuditingEntityListener.class)
public class Collect {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer collectId;
private Integer collectArticleId;
private Integer collectUserId;
@CreatedDate
private Date collectTime;
private Integer collectState;
}
然后又在前端界面中给它指定值,导致报错
// 收藏
collect:{
collectArticleId: 0,
collectId: 0,
collectState: 0,
collectTime: "",
collectUserId: 0
} ,
3. 解决步骤
将 collectId和collectTime去掉即可,