У меня есть 2 лица.City
@Entity
@Table(name = "cities")
public class City implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "city_id")
private Long id;
@Column(nullable = false, length = 20)
private String name;`enter code here`
@Column(nullable = false)
private Long population;
@OneToMany(mappedBy = "city", fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE })
private List<School> schools = new ArrayList<>();
public void addSchool(School school){
school.setCity(this);
getSchools().add(school);
}
и школа
@Entity
@Table(name = "schools")
public class School implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "school_id")
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String headTeacher;
@ManyToOne()
@JoinColumn(name = "city_id")
private City city;
CityDao и SchoolDao, расширяющие GenericDao
@Transactional
public abstract class GenericDao<T,K> {
@PersistenceContext
EntityManager entityManager;
public void save(T entity){
entityManager.persist(entity);
}
public T get(K key){
T find = entityManager.find(type, key);
return find;
}
public void remove(T entity) {
T managedEntity = entityManager.merge(entity);
entityManager.remove(managedEntity);
}
Я создал экземпляры и сохранил их в MySQL
City city = new City("Warsaw", 200000L);
School school1 = new School("School1", "Jacob");
School school2 = new School("School2","Somebody");
CityDao cityDao = ctx.getBean(CityDao.class);
city.addSchool(school1);
city.addSchool(school2);
cityDao.save(city);
И когда я пытаюсь удалить school1 или school2, ничего не происходит.Entity school1 все еще находится в базе данных.Там нет никаких ошибок.
School school = schoolDao.get(1L);
schoolDao.remove(school);