简体   繁体   English

Spring 数据 JPA 无法找到带有 id 的 object

[英]Spring Data JPA unable to find object with id

I'm using JPA + Hibernate + Spring Data JPA on my project for working with database (MySQL).我正在使用 JPA + Hibernate + Spring 数据 Z9CE3D1BD8890F16A0C44809359508 用于我的项目数据库(MySQL)。 Recently I've got an error which says:最近我有一个错误说:

org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.kanda.mindwire.domain.results.CognitiveResult with id 1700; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.kanda.mindwire.domain.results.CognitiveResult with id 1700

at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:379) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:257) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) ~[spring-tx-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149) ~[spring-data-jpa-2.2.3.RELEASE.jar:2.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at com.sun.proxy.$Proxy157.findByCompany(Unknown Source) ~[na:na]
at com.kanda.mindwire.service.employee.EmployeeService.findWithFilter(EmployeeService.java:210) ~[classes/:1.0-SNAPSHOT]

The code is trying to fetch the list of Employee entity which is having a OneToOne relation with CognitiveResult .该代码试图获取与CognitiveResult具有OneToOne关系的Employee实体列表。 I was thinking that it might be that there are Employee row with cognitive_id=1700 but when I query my db I see that there are no such row.我在想可能是有Employee行, cognitive_id=1700但是当我查询我的数据库时,我发现没有这样的行。

The question is from where hibernate takes this id and how to fix it?问题是 hibernate 从哪里获取这个id以及如何修复它?

Here is my code: Employee.java这是我的代码: Employee.java

@Table(uniqueConstraints = @UniqueConstraint(columnNames = {Employee_.EMAIL}))
@Entity
@Data
public class Employee extends BaseEmployee {

@Column
private String email;
....
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "cognitive_id", referencedColumnName = "id")
private CognitiveResult cognitiveResult;
...
}

CognitiveResult.java认知结果.java

@Entity
@Table(name = "cognitive_results")
@Data
public class CognitiveResult extends BaseAssesment {
...

@OneToOne(mappedBy = "cognitiveResult")
private Employee employee;

@PreRemove
public void removeCognitiveForEmployee() {
    if (employee != null) {
        employee.setCognitiveResult(null);
    }
}
...
}

EmployeeRepository.java EmployeeRepository.java

public interface EmployeeRepository extends BaseRepository<Employee> {
...
    List<Employee> findByCompany(Company company);
...
}

Company.java公司.java

@Entity
@Data
public class Company extends BaseSettingsEntity {
...
@OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
private Set<Employee> employees = new HashSet<>();
/**
 * Logic for syncing employees
 * @param employee
 */
 public void removeEmployee(Employee employee) {
    if (!employees.contains(employee)) {
        return;
    }

    employees.remove(employee);
    employee.setCompany(null);
 }

 public void addEmployee(Employee employee) {
    if (employees.contains(employee)) {
         return;
    }

    employees.add(employee);
    employee.setCompany(this);
 }
...
}

All of my domain models inherit from BaseEntity.java我所有的域模型都继承自BaseEntity.java

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Entity
@Data
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(updatable = false, nullable = false)
protected Long id;
...
}

And the exception occurs while calling findByCompany:调用 findByCompany 时发生异常:

@Slf4j
public class EmployeeService extends BaseEntityService<Employee> {

private final EmployeeRepository repo;

public Map<String, Map<EmployeeJob, List<Employee>>> findWithFilter(EmployeeFilterWrapper filter, String username) {
    List<Employee> employeeList;
    User user = userService.findByUsername(username);
    Company company = user.getCompany();
    if (company == null)
        throw new InvalidCompanyException("Company not assigned for a user!");

    if (filter != null && filter.getDivisionsFilter() != null && CollectionUtils.isNotEmpty(filter.getDivisionsFilter().getDivisions())) {
        employeeList = repo.findEmployeeByDivisionNamesAndCompany(filter.getDivisionsFilter().getDivisions(), company.getName());
    } else {
        employeeList = repo.findByCompany(company);
    }
...
}

Found an issue.发现一个问题。 There where a link to missing cognitive_id in another table and it is missing because I was clearing those entites directly in db recently, but forgot that they reference other table.那里有一个链接到另一个表中缺少的cognitive_id并且它丢失了,因为我最近直接在db 中清除了这些实体,但忘记了它们引用了另一个表。 It was a Supervisors table which is inherited from Employee这是一个从Employee继承的Supervisors

@Entity
@Table(name = "supervisors")
@Data
public class Supervisor extends Employee {
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM