I was thinking to use @JoinTable to be able displaying the name of kid when I search on his parent but a little struggling with it.
The program stores kids and one of their parents (or both) and when I search the name of the parent the program should display the name of kid (or kids).
Two interfaces needed:
- name of parents and kids (name of parent is unique, so in case if it already exists then we just insert the name of the kid (and its parent_id)
when I search on the name of the parent the program displays his/her kid (or kids).
PARENTS table:
ID (PK, NN, AI, int)
NAME (NN, String)
- KIDS table:
ID (PK, NN, AI, int)
NEV (NN, String)
PARENTS_ID (NN, int)
The program should use a FK and OneToMany, ManyToOne connection which uses search and save.
I would welcome any suggestions about what is the best practice to finish the code.
Parents.java
@Entity
public class Parents {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long Id;
@NotNull
private String firstName;
@NotNull
private String lastName;
@OneToMany(fetch = FetchType.LAZY, mappedBy="parents")
private List<Kids> kids;
// constructor + getters & setters
Kids.java
@Entity
public class Kids {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long Id;
@NotNull
private String firstName;
@NotNull
private String lastName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parents_id")
@NotNull
private Parents parents;
public Kids() {
}
public Kids(String firstName, String lastName, Parents parents) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.parents = parents;
}
// getters & setters
data.sql
INSERT INTO Parents (first_name, last_name) VALUES ('Viz','Elek');
INSERT INTO Parents (first_name, last_name) VALUES ('Locsolok','Anna');
INSERT INTO Parents (first_name, last_name) VALUES ('Kezmuves','Kelemen');
INSERT INTO Kids (first_name, last_name, parents_id) VALUES ('Nagy','Zolika', (SELECT id FROM Parents WHERE last_name = 'Elek'));
INSERT INTO Kids (first_name, last_name, parents_id) VALUES ('Cserkesz','Misike', (SELECT id FROM Parents WHERE last_name = 'Elek'));
INSERT INTO Kids (first_name, last_name, parents_id) VALUES ('Mézesb','Ödönke', (SELECT id FROM Parents WHERE last_name = 'Anna'));
KidsRepo.java
public interface KidsRepo extends CrudRepository<Kids, Long> {
List<Kids> findKidsByParentId(Parents Id);
}
HomeController.java
@Controller
public class HomeController {
KidsRepo kidsRepository;
@Autowired
public void setKidsRepository(KidsRepo kidsRepository) {
this.kidsRepository = kidsRepository;
}
}
KidsService.java
@Service
public class KidsService {
KidsRepo kidsRepository;
ParentsRepo parentsRepository;
@Autowired
public void setKidsRepository(KidsRepo kidsRepository) {
this.kidsRepository = kidsRepository;
}
@Autowired
public void setParentsRepository(ParentsRepo parentsRepository) {
this.parentsRepository = parentsRepository;
}
public List<Kids> getKids(Parents id) {
return kidsRepository.findKidsByParentId(id);
}
}