Spring Data JPA ManyToOne query null - PullRequest
0 голосов
/ 26 мая 2020

Я начал изучать Spring Boot, я создал две сущности Invoice и YearDate

Когда я пытаюсь выполнить поиск по году (id), в моем запросе журнала я получил null (см. Эту часть log query)

http://localhost:8080/appapi/invoices/search/findByYearId?year=1

from invoice invoice0_ left outer join year_date yeardate1_ on invoice0_.year_id=yeardate1_.id where yeardate1_.id is null limit?

Я использую Lombok также для геттеров и сеттеров

Вот все объекты моего класса, SQL таблицы и интерфейс JpaRepository:

SQL внешний ключ:

KEY `fk_year` (`year_id`),
  CONSTRAINT `fk_year` FOREIGN KEY (`year_id`) REFERENCES `YearDate` (`id`)

Класс YearDate:

@Entity
@Table(name="YearDate")
@Data
public class YearDate {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "year_value")
    private String yearValue;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "year")
    private Set<Invoice> invoices;
}

Класс счета:

@Entity
@Table(name="invoice")
@Data
public class Invoice {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "year_id", nullable = false)
    private YearDate year;

    @Column(name = "description")
    private String description;
}


**And The Invoice Interface:**

@CrossOrigin("http://localhost:4200")
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {

    Page<Invoice> findByYearId(@RequestParam("year") Long id, Pageable page);

}

Ответы [ 3 ]

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

Я отключил Ломбок, он работает

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

попробуйте передать ему объект Year, а не id, лучше

@CrossOrigin("http://localhost:4200")
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
    Page<Invoice> findByYear(YearDate year, Pageable page);
}

и в вашем сервисе получите этот год, например, я создаю метод getYears в сервисе:

@Service
public class YearService{

@Autowired
private YearRepository yearRepository;
@Autowired
private InvoiceRepository invoiceRepository;

getYears(idYear:Long){
YearDate yearParam=yearRepository.findById(id).get();
Page<Invoice> invoices=invoiceRepository.findByYear(yearParam,YourPagination)
}

}
0 голосов
/ 26 мая 2020

Работа для меня.

попытаться извлечь вызов в контроллере отдыха и параметры журнала

@GetMapping(value = "/invoices")
  public Page<Invoice> getInvoices(@RequestParam("yearId") Long yearId) {
        Page<Invoice> byYearId = invoiceRepository.findByYearId(yearId, PageRequest.of(0, 10));
        return byYearId;
}


public interface InvoiceRepository extends JpaRepository<Invoice, Long> {

    Page<Invoice> findByYearId(Long id, Pageable page);
}


 @ManyToOne
    @JoinColumn(name = "year_id", nullable = false)
   @JsonIgnoreProperties("invoices")
    private YearDate year;

 @OneToMany(mappedBy = "year")
    @JsonIgnoreProperties("year")
    private Set<Invoice> invoices;

Сгенерировано SQL:

Hibernate: 
    select
        invoice0_.id as id1_0_,
        invoice0_.description as descript2_0_,
        invoice0_.name as name3_0_,
        invoice0_.year_id as year_id4_0_ 
    from
        invoice invoice0_ 
    left outer join
        year_date yeardate1_ 
            on invoice0_.year_id=yeardate1_.id 
    where
        yeardate1_.id=? limit ?
Hibernate: 
    select
        yeardate0_.id as id1_5_0_,
        yeardate0_.year_value as year_val2_5_0_ 
    from
        year_date yeardate0_ 
    where
        yeardate0_.id=?

-> ДОБАВИТЬ @JsonIgnoreProperties («счета») и @JsonIgnoreProperties («год») к объектам, чтобы избежать бесконечного json повторного обращения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...