Just_another_developer
Just_another_developer

Reputation: 5947

How to structure an Entity in Spring boot/ JPA having multiple foreign keys?

I hava a table "Details" which has information from "City", "Town", "branch" tables. They all are one time configuration tables and their information is constant.They never need to be updated.

"Details" table have foreign keys references from these tables like "city_id","town_id","branch_id".

Now the problem is, when the data uploads for "details", it has "City_name","town_name" and "branch name".I need to convert this data in Ids to store them in "details"

What should I do to achieve my objective?

Example:

 Data uploads: "City name","town name", "branch name".

City:

id  | City_name
 1  | city name
 2  | city name 2

Town:

id  | Town_name
 1  | town name
 2  | town name 2

Branch

id  | branch_name
 1  | branch name
 2  | branch name 2

Now, data that must be stored in "details"

details_id | city_id | town_id | branch_id
 1         |1        |1        |1

Upvotes: 1

Views: 131

Answers (1)

marknote
marknote

Reputation: 1077

You need to fetch referred objects and then create the entity and save it. Should be something like:

City foundCity = CityRepository.findByName(cityName).orElseThrow(() -> new EnityNotFoundException("City not found"));
...
Detail detail = new Detail();
detail.setCity(foundCity);
...
detailRepository.save(detail);

If you have big number of Details to create and the number of referred objects are not so huge, you might need to load all referred objects into memory before proceeding. Like

List<City> cities = cityRepository.findAll();
...

List<Detail> detailsToSave = new ArrayList<>();

City foundCity = cities.stream()
        .filter(item -> name.equals(item.getName()))
        .orElseThrow(() -> new EnityNotFoundException("City not found"));
    ...
    Detail detail = new Detail();
    detail.setCity(foundCity);
    ...
    detailsToSave.add(detail);
    ....

 detailRepository.saveAll(detailsToSave);

Upvotes: 3

Related Questions