我拥有的内容:
多个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如何填充客户端文件?