Spring Data JPA не может найти объект с идентификатором - PullRequest
0 голосов
/ 04 мая 2020

Я использую JPA + Hibernate + Spring Data JPA в своем проекте для работы с базой данных (MySQL). Недавно я получил сообщение об ошибке:

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]

Код пытается получить список сущности Сотрудник , которая имеет отношение OneToOne с CognitiveResult . Я думал, что, возможно, существует строка Employee с cognitive_id = 1700 , но когда я запрашиваю свою базу данных, я вижу, что такой строки нет.

вопрос откуда hibernate берет этот id и как это исправить?

Вот мой код: Сотрудник. 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

@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);
    }
}
...
}

Репозитарий сотрудников. java

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

Company. 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);
 }
...
}

Все модели моего домена наследуются от 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;
...
}

И исключение возникает при вызове 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);
    }
...
}

1 Ответ

0 голосов
/ 04 мая 2020

Найдена проблема. Там, где ссылка на пропущенную cognitive_id в другой таблице отсутствует, и она отсутствует, потому что я недавно очищал эти объекты непосредственно в db, но забыл, что они ссылаются на другую таблицу. Это была таблица Supervisors, которая унаследована от Employee

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