A good solution will make the code bidirectional, as you have already indicated, and use the annotation "@PrePersist" to set the identifier to the "Rules" objects. Sort of:
Rule.java
@Entity public class Rule implements Serializable { @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) private Long id; private String description; @ManyToOne private Filter filter;
Filter.java
@Entity public class Filter implements Serializable { @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) private Long id; @OneToMany( fetch = FetchType.EAGER, orphanRemoval = true, cascade = { CascadeType.ALL }, mappedBy="filter" ) private List<Rule> rules = new ArrayList<>(); @PrePersist public void prePersist() { if (rules != null) { rules.forEach(item -> item.setFilter(this)); } }
FilterRepository.java
@Repository public interface FilterRepository extends JpaRepository<Filter, Integer> { }
AnUnitTest.java
@RunWith(SpringRunner.class) @SpringBootTest public class AnUnitTest { @Autowired private FilterRepository filterRepository; @After public void clearDatabase() { bodyPartRespository.deleteAll(); filterRepository.deleteAll(); } @Test public void testFilterRules() { Rule aRule = Rule.builder() .description("A") .build(); Rule anotherRule = Rule.builder() .description("B") .build(); Filter filter = Filter.builder() .rules(Arrays.asList(aRule, anotherRule)) .build(); filterRepository.saveAndFlush(filter); List<Filter> all = filterRepository.findAll(); all.forEach(System.out::println); } }
The above code is great for me.
I hope this solves your problem.
Greetings, Nicholas.
source share