DomainClassConverter не работает в Spring Boot - PullRequest
2 голосов
/ 10 июля 2020

У меня очень простой проект Spring Boot MVC, в котором я пытаюсь использовать DomainClassConverter для прямой загрузки Entity. Но похоже, что DomainClassConverter не найден. У меня возникает следующая ошибка при доступе к URL-адресу localhost: 8080 / one / 2:

Невозможно преобразовать значение типа java .lang.String в требуемый тип com.example. test.data.Customer ': подходящих редакторов или стратегии преобразования не найдено

Но DomainClassConverter должен быть включен с помощью Spring Boot и управлять преобразованием.

Я также попытался включить его явно через @ Аннотации EnableSpringDataWebSupport, но она тоже не сработала.

Вот мой код контроллера:

@Controller
public class TestController {

    @Autowired
    private CustomerRepository customerRepository;

    @GetMapping("/all")
    public void all(Model model) {
        Iterable<Customer> customers=customerRepository.findAll();
        model.addAttribute("customers",customers);
    };

    @GetMapping("/one/{customer_id}")
    public void one(@PathVariable("customer_id") Customer customer, Model model) {
        model.addAttribute("customer",customer);
    };
}

Customer coode:

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Getter
    private Long id;

    @Getter
    @Setter
    private String firstName;

    @Getter
    @Setter
    private String lastName;

    protected Customer() {
    }

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

}

CustomerREpositoy:

public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);

    Customer findById(long id);
}

Приложение:

@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }
}

И наконец build.graddle:

plugins {
    id 'org.springframework.boot' version '2.3.1.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
//    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
//    testImplementation 'org.springframework.security:spring-security-test'
}

test {
    useJUnitPlatform()
}

Есть идеи?

1 Ответ

0 голосов
/ 10 июля 2020

вы пытаетесь получить customer_id (переменную пути) как объект Customer. следовательно, получите указанную выше ошибку при попытке доступа к localhost:8080/one/2.

измените тип данных customer_id (переменная пути) на соответствующий тип данных (String, int et c.) следующим образом:

@GetMapping("/one/{customer_id}")
public void one(@PathVariable("customer_id") String customerId, Model model) {
    ----
};
...