Hibernate:有趣的测验,可插入= false&更新=假

时间:2013-11-21 10:35:59

标签: java hibernate hibernate-mapping

我拥有的内容:

多个Owner个实体,其中包含Client个子类型实体之一。我需要客户端实体的每个子类型只能保存到数据库一次,所以我使用insertable = false, updatable = false

@Entity
@Table(name = "Client")
public class Client implements Serializable {

    @Id
    @Column(name = "id")
    private String id = this.getClass().getSimpleName();

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

    //getters & setters
}

@Entity
@Table(name = "Client")
public class AngryClient extends Client {
}

@Entity
@Table(name = "Client")
public class SilentClient extends Client {
}

@Entity
@Table(name = "Owner")
public class Owner {

    @Id
    @SequenceGenerator(name = "sequence", sequenceName = "_vacancy")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
    @Column(name = "id")
    private int id;

    @ManyToOne
    @JoinColumn(name = "id", insertable = false, updatable = false)

     //getters & setters
}

我无法掌握的内容:

由于insertable = false, updatable = false,当我们保存所有者时,客户端将无法保存。它可以在数据库中轻松检查。 owner表中存储的唯一列是id

那么Hibernate如何知道哪个Client对应哪个Owner

Session session = sessionFactory.openSession();
session.beginTransaction();

Owner owner1 = new Owner();
Owner owner2 = new Owner();
Client client1 = new AngryClient();
Client client2 = new SilentClient();
owner1.setClient(client1);
owner2.setClient(client2);
session.save(owner1); //client1 isn't saved
session.save(owner2); //client2 isn't saved
int owner1Id = owner1.getId();
session.getTransaction().commit(); //client table is empty

Session session1 = sessionFactory.openSession();
Owner owner = (Owner) session1.get(Owner.class, owner1Id);
System.out.println(owner.getClient());  //HOW DOES IT WORK?! (owner.getClient() returns me AngryClient)

问题:

它是如何工作的?或者当我们session.get(Owner.class, owner1Id)时,Hibernate如何填充客户端文件?

0 个答案:

没有答案