关于hibernate的单向映射问题

@Entity(name = "person")
public class Person1 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true)
private List<Phone1> phones = new ArrayList<Phone1>();

public List<Phone1> getPhones() {
    return phones;
}

}

@Entity(name = "phone")
public class Phone1 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "number")
private String number;

public Phone1(String number) {
    this.number = number;
}

public Phone1(){};

public Long getId() {
    return id;
}

public String getNumber() {
    return number;
}   

}

@Test
public void test1(){
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Person1 person = new Person1();
    Phone1 phone1 = new Phone1( "123-456-7890" );
    Phone1 phone2 = new Phone1( "321-654-0987" );

    person.getPhones().add( phone1 );
    person.getPhones().add( phone2 );
    session.save(person);
    session.getTransaction().commit();

    session.beginTransaction();
    person.getPhones().remove( phone1 );

    session.getTransaction().commit();
    session.close();

}

    以上分别是两张对应的实体类,第3个是我写的测试用例。运行之后的SQL语句是
         insert into person values ( )
       insert into phone (number) values (?)
       insert into phone (number) values (?)
       insert into person_phone (person_id, phones_id) values (?, ?)
       insert into person_phone (person_id, phones_id) values (?, ?)
   delete from person_phone where person_id=?
       insert into person_phone (person_id, phones_id) values (?, ?)
       delete from phone where id=?

        可以看出如果要移除Person的一个号码,会先删除中间表所有与Person有关的数据后再插入。比如person有phone1和phone2两个号码,现在执行操作删除phone1,那么hibernate的做法是会先在中间表删除person与phone的所有关联,然后再插入phone2的数据。

        想知道Hibernate为什么会这样执行呢?效率不是太低了吗?

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐