com.fasterxml.jackson.databind.JsonMappingException: невозможно найти модель с идентификатором - PullRequest
0 голосов
/ 02 ноября 2018

Проблема в том, что, когда я запускаю запрос:

    String username = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
    User user = userRepository.findByUsername(username);
    return new ResponseEntity<>(user, HttpStatus.OK);

Я получаю эту ошибку:

2018-11-02 13:43:48.096  WARN 9704 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Unable to find com.getmydrivercard.getmydrivercard.models.DrivingLicense with id eec35b46-8e47-4d89-bcf1-027a7ed3403b; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unable to find com.getmydrivercard.getmydrivercard.models.DrivingLicense with id eec35b46-8e47-4d89-bcf1-027a7ed3403b (through reference chain: com.getmydrivercard.getmydrivercard.models.User["drivingLicense"]->com.getmydrivercard.getmydrivercard.models.DrivingLicense_$$_jvst134_6["recordId"])]

Вот мои модели:

package com.getmydrivercard.getmydrivercard.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.getmydrivercard.getmydrivercard.validators.email.ValidEmail;
import com.getmydrivercard.getmydrivercard.validators.password.ValidPassword;
import com.getmydrivercard.getmydrivercard.validators.username.ValidUsername;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

@Entity
@Table(name = "users")
public class User extends Model {
    private static final String EMPTY_STRING = "";

    @NotBlank
    @ValidUsername
    private String username;

    @NotBlank
    //@ValidPassword
    private String password;

    @NotBlank
    @ValidEmail
    private String email;

    @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    @NotNull
    private DrivingLicense drivingLicense;

    @OneToOne
    private PersonalDetails personalDetails;

    private String comments;

    protected User(){}

    public User(String username, String password, String email, DrivingLicense drivingLicense){
        setUsername(username);
        setPassword(password);
        setEmail(email);
        setComments(EMPTY_STRING);
        setDrivingLicense(drivingLicense);
    }

    public PersonalDetails getPersonalDetails() {
        return personalDetails;
    }

    public void setPersonalDetails(PersonalDetails personalDetails) {
        this.personalDetails = personalDetails;
    }

    public DrivingLicense getDrivingLicense() {
        return drivingLicense;
    }

    public void setDrivingLicense(DrivingLicense drivingLicense) {
        this.drivingLicense = drivingLicense;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

и водительские права:

package com.getmydrivercard.getmydrivercard.models;

import com.getmydrivercard.getmydrivercard.enums.DrivingLicenseCategory;
import com.getmydrivercard.getmydrivercard.enums.EUCountry;
import com.getmydrivercard.getmydrivercard.helpers.Generator;
import com.getmydrivercard.getmydrivercard.validators.drivinglicensenumber.ValidDrivingLicenseNumber;
import com.getmydrivercard.getmydrivercard.validators.issuingauthority.ValidIssuingAuthority;
import com.getmydrivercard.getmydrivercard.validators.string.ValidString;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Entity
@Table(name = "driving_licenses")
public class DrivingLicense extends Model {
    private static final int DRIVING_LICENSE_NUMBER_LENGTH = 9;

    @NotNull
    private EUCountry issuingCountry;

    @NotBlank
    @ValidDrivingLicenseNumber
    private String drivingLicenseNumber;

    @NotNull
    private DrivingLicenseCategory drivingLicenseCategory;

    @NotNull
    private Date dateOfExpiry;

    @NotBlank
    @ValidIssuingAuthority
    private String issuingAuthority;

    protected DrivingLicense(){}

    public DrivingLicense(EUCountry issuingCountry, DrivingLicenseCategory drivingLicenseCategory, String issuingAuthority){
        setIssuingCountry(issuingCountry);
        setDrivingLicenseNumber(getNewRandomDrivingLicenseNumber());
        setDateOfExpiry(new Date());
        setDrivingLicenseCategory(drivingLicenseCategory);
        setIssuingAuthority(issuingAuthority);
    }

    public DrivingLicenseCategory getDrivingLicenseCategory() {
        return drivingLicenseCategory;
    }

    public void setDrivingLicenseCategory(DrivingLicenseCategory drivingLicenseCategory) {
        this.drivingLicenseCategory = drivingLicenseCategory;
    }

    public Date getDateOfExpiry() {
        return dateOfExpiry;
    }

    public void setDateOfExpiry(Date dateOfExpiry) {
        Calendar c = Calendar.getInstance();
        c.setTime(dateOfExpiry);
        c.add(Calendar.YEAR, 4);
        dateOfExpiry = c.getTime();
        this.dateOfExpiry = dateOfExpiry;
    }



    public String getIssuingAuthority() {
        return issuingAuthority;
    }

    public void setIssuingAuthority(String issuingAuthority) {
        this.issuingAuthority = issuingAuthority;
    }

    public String getDrivingLicenseNumber() {
        return drivingLicenseNumber;
    }

    public void setDrivingLicenseNumber(String drivingLicenseNumber) {
        this.drivingLicenseNumber = drivingLicenseNumber;
    }

    public EUCountry getIssuingCountry() {
        return issuingCountry;
    }

    public void setIssuingCountry(EUCountry issuingCountry) {
        this.issuingCountry = issuingCountry;
    }

    private String getNewRandomDrivingLicenseNumber(){
        Generator generator = new Generator();
        return generator.getRandomStringWithDigits(DRIVING_LICENSE_NUMBER_LENGTH);
    }
}

Если вам нужны подробности, я могу предоставить их. Я пытался изменить тип выборки, но все равно не работает. Мне интересно, есть ли проблемы с геттерами и сеттерами, но я думаю, что все в порядке. Вот почему я оставил их.

Класс моей модели:

package com.getmydrivercard.getmydrivercard.models;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.UUID;

@MappedSuperclass
public abstract class Model {

    @Id
    @GeneratedValue
    private UUID recordId;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    private Date recordCreated;
    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    private Date recordLastTimeEdited;

    public Model() {
        setRecordCreated(new Date());
        setRecordLastTimeEdited(new Date());
    }

    public UUID getRecordId() {
        return recordId;
    }

    public void setRecordId(UUID recordId) {
        this.recordId = recordId;
    }

    public Date getRecordCreated() {
        return recordCreated;
    }

    public void setRecordCreated(Date recordCreated) {
        this.recordCreated = recordCreated;
    }

    public Date getRecordLastTimeEdited() {
        return recordLastTimeEdited;
    }

    public void setRecordLastTimeEdited(Date recordLastTimeEdited) {
        this.recordLastTimeEdited = recordLastTimeEdited;
    }
}

EDIT: изменил тип Id на Long, и это сработало. До сих пор не знаю, почему.

...