如何在“一对多”关联中删除休眠中的唯一父母而不是父母?

时间:2019-07-04 19:43:25

标签: java mysql hibernate jpa associations

我有2个实体。城市

 @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;

扩展GenericDao的CityDao和SchoolDao

 @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时,什么也没发生。实体school1仍在数据库中。没有任何错误。

School school = schoolDao.get(1L);
       schoolDao.remove(school);

0 个答案:

没有答案