Questions about how to access multiple IDs for Spring Data JPA

Asked 2 years ago, Updated 2 years ago, 83 views

We are developing a web system using SpringBoot.
I know how to retrieve data from JPA findById (ID id) in general, but
I would like to set Entity with multiple @IDs to retrieve data with multiple IDs.
I don't know how to implement it.There are not many samples...
In this case, do I use findAllById (Iterable id)?

Supplemental
I'm looking for a way other than findBy△△And 〇 〇() method

java spring jpa

2022-09-30 19:18

1 Answers

Annotation @IdClass allows you to express compound principal keys


@Entity
@IdClass(FullName.class)
public class Person {

    @Id
    private String sei;
    @Id
    private String mei;

    private LocalDate birthday;

    // getters and setsters
}
public class FullName implements Serializable {
    /** Last Name*/
    private String sei;
    /** First Name*/
    private String mei;
}

However, if you use the Spring Data JPA repository interface at this time, as in the case of the monomial main key,

@Repository
public interface PersonRepository extensions JpaRepository <Person, FullName > {
}

The definition is as follows:
Therefore, the method of searching by the primary key remains the same, using the findById method, which takes the primary key type (FullName) as the argument.

@RestController
@RequestMapping("")
@RequiredArgsConstructor
public class MyController {

    private final personRepository personRepository;

    @GetMapping
    public Optional <Person>index(){
        return personRepository.findById(new FullName("Nitobe", "Inazukuri"));
    }
}

(sample implementation)


2022-09-30 19:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.