0

I am dealing with one issue. I have relation one-to-many and in my case it looks like that:


@Data
@Entity
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String title;
    ...
    @OneToMany(mappedBy = "event", cascade = ALL)
    List<TimePeriod> dates;

and TimePeriod entity looks following:

@Entity
@Data
public class TimePeriod {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    ...
    @ManyToOne
    private Event event;
}

My JPA repo looks like that:

@Repository
public interface TimePeriodRepository extends JpaRepository<TimePeriod, Long>
{
}

When i execute following code:

event.getDates().stream().forEach(d -> {
            timePeriodRepository.deleteById(d.getId());
        });

I dont see that records were removed from database. They are still there. I understand that TimePeriod is owning side in my case, so i understand it should work.

I am operating mainly od event entity, why i put there cascade.ALL option.

But when i had a cascade.ALL also on TimePeriod then not only related records were removed but also EVENT.

Another way which i tried i upadated event side like:

event.setDates(new ArrayList<>());

but after when i save event i was still able to see those date records in database.

Can someone let me know what im doing wrongly ?

Johnny
  • 11
  • 4

3 Answers3

0

Have you checked for a DataIntegrityViolationException when you delete the dates?

You should try to remove all dates from the event, save the event and then delete each TimePeriod instance:

List<TimePeriod> dates = event.getDates();
event.setDate(List.of());
eventRepository.merge(event);
dates.stream().forEach(d -> {
    timePeriodRepository.deleteById(d.getId());
});
Francesco Rogo
  • 167
  • 2
  • 8
  • I did not see any exceptions like data integrity. But when i did like u suggested it worked. Do i always need to update two sides? i thougth it can be done by one side, isnt it? – Johnny Oct 22 '20 at 10:44
  • You need to when you don't want the cascading behaviour to take place. – Francesco Rogo Oct 23 '20 at 15:45
0

Does Delete Not Working with JpaRepository answer your question? Your situation with bidirectional references looks similar.

Sebastiaan van den Broek
  • 5,818
  • 7
  • 40
  • 73
0

But when i had a cascade.ALL also on TimePeriod then not only related records were removed but also EVENT.

The meaning of CascadeType.ALL is that the persistence will propagate all operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

Instead I think you should try orphanRemoval.

Aman
  • 1,627
  • 13
  • 19