Hibernate一對一關聯對映(註解)
阿新 • • 發佈:2018-12-24
hibernate一對一關聯對映有兩種方式,一種是基於外來鍵方式(常用),一種是基於主鍵方式
一、首先我們來看基於外來鍵一對一關聯對映:
1.資料表關聯對映圖
基於外來鍵的一對一關聯對映,維護端(有外來鍵方)可以維護雙方關聯,對雙方進行刪除操作,而被維護端(無外來鍵方)則不可以
2.Customer實體類,維護端(有外來鍵方)
- @Entity
- @Table(name = "T_FOREIGN_CUSTOMER")
- publicclass Customer {
- privateint id;
-
private
- private Referee referee;
- @Id
- @GeneratedValue(strategy = GenerationType.TABLE, generator = "T_FOREIGN_CUSTOMER_GEN")
-
@TableGenerator(name = "T_FOREIGN_CUSTOMER_GEN", table = "TB_GENERATOR", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VALUE", pkColumnValue =
- publicint getId() {
- return id;
- }
- publicvoid setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- publicvoid setName(String name) {
-
this.name = name;
- }
- /**
- * 預設外來鍵名referee_id
- * @OneToOne public Referee getReferee() { return referee; }
- * @return
- */
- /**
- * /使用新的外來鍵名:referee1_id
- * @OneToOne
- * @JoinColumn(name="referee1_id") public Referee getReferee() { return
- * @return
- */
- @OneToOne
- @JoinColumn(name = "referee_id")
- // 維護端
- public Referee getReferee() {
- return referee;
- }
- /**
- * 從上面的程式碼可以看出,getReferee方法使用了@OneToOne進設定
- * 在裝載Customer物件的同時,Referee物件會被同時裝載,而預設的外來鍵欄位就是Customer類中的referee屬性名+"_"+id
- * 也就是referee_id
- * @param referee
- */
- publicvoid setReferee(Referee referee) {
- this.referee = referee;
- }
- }
- @Entity
- @Table(name="T_FOREIGN_REFEREE")
- publicclass Referee {
- privateint id;
- private String name;
- private Customer customer;
- @Id
- @GeneratedValue(strategy = GenerationType.TABLE, generator = "T_FOREIGN_REFEREE_GEN")
- @TableGenerator(name = "T_FOREIGN_REFEREE_GEN", table = "TB_GENERATOR", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VALUE", pkColumnValue = "T_FOREIGN_REFEREE_GEN", allocationSize = 1)
- publicint getId() {
- return id;
- }
- publicvoid setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- publicvoid setName(String name) {
- this.name = name;
- }
- //mappedBy表示被維護端
- @OneToOne(mappedBy="referee")
- public Customer getCustomer() {
- return customer;
- }
- publicvoid setCustomer(Customer customer) {
- this.customer = customer;
- }
- }
- @Service("customerService")
- @Transactional
- publicclass CustomerService {
- @Resource
- private SessionFactory sessionFactory;
- publicvoid saveForgin() {
- Customer customer = new Customer();
- customer.setName("微軟");
- Referee referee = new Referee();
- referee.setName("趙軍");
- customer.setReferee(referee);
- referee.setCustomer(customer);
- // 先儲存無外來鍵方
- sessionFactory.getCurrentSession().persist(referee); //如果這裡不想一個物件一個物件儲存,想要級聯自動儲存,需要在儲存的物件那一方新增cascade=CascadeType.ALL來級聯儲存操作
- sessionFactory.getCurrentSession().persist(customer);
- }
- public Customer getCustomer(int id) {
- return (Customer) sessionFactory.getCurrentSession().get(
- Customer.class, id);
- }
- public Referee getReferee(int id) {
-
return (Referee) sessionFactory.getCurrentSession().get(Referee.