ไฮเบอร์เนตการสอนคำอธิบายประกอบหนึ่งถึงหลาย

1. บทนำ

บทช่วยสอน Hibernate ฉบับย่อนี้จะนำเราไปสู่ตัวอย่างของการทำแผนที่แบบหนึ่งต่อกลุ่มโดยใช้คำอธิบายประกอบ JPA ซึ่งเป็นทางเลือกสำหรับ XML

นอกจากนี้เรายังจะได้เรียนรู้ว่าความสัมพันธ์แบบสองทิศทางคืออะไรพวกเขาสามารถสร้างความไม่สอดคล้องกันได้อย่างไรและแนวคิดในการเป็นเจ้าของสามารถช่วยได้อย่างไร

2. คำอธิบาย

พูดง่ายๆก็คือการแมปแบบหนึ่งต่อหลายหมายความว่าแถวหนึ่งในตารางถูกแมปกับหลายแถวในตารางอื่น

ลองดูแผนภาพความสัมพันธ์ของเอนทิตีต่อไปนี้เพื่อดูการเชื่อมโยงแบบหนึ่งต่อกลุ่ม:

สำหรับตัวอย่างนี้เราจะใช้ระบบรถเข็นที่เรามีตารางสำหรับรถเข็นแต่ละรายการและอีกตารางสำหรับสินค้าแต่ละรายการ รถเข็นหนึ่งคันสามารถมีสินค้าได้หลายรายการดังนั้นเราจึงมีการทำแผนที่แบบหนึ่งต่อหลายรายการ

วิธีนี้ทำงานอยู่ที่ระดับฐานข้อมูลคือเรามีcart_idเป็นคีย์หลักในรถเข็นโต๊ะและยังเป็นcart_idเป็นคีย์ต่างประเทศในรายการ

วิธีที่เราทำมันในรหัสอยู่กับ@OneToMany

มาแมปคลาสCartกับอ็อบเจ็กต์Itemsในลักษณะที่สะท้อนความสัมพันธ์ในฐานข้อมูล:

public class Cart { //... @OneToMany(mappedBy="cart") private Set items; //... }

นอกจากนี้เรายังสามารถเพิ่มการอ้างอิงไปยังรถเข็นในรายการโดยใช้@ManyToOneทำให้เป็นความสัมพันธ์แบบสองทิศทาง วิธีการแบบสองทิศทางที่เราสามารถที่จะเข้าถึงรายการจากรถและรถจากรายการ

mappedByคุณสมบัติคือสิ่งที่เราใช้ในการบอก Hibernate ซึ่งตัวแปรเราจะใช้เพื่อเป็นตัวแทนระดับผู้ปกครองเด็กในชั้นเรียนของเรา

เทคโนโลยีและไลบรารีต่อไปนี้ใช้เพื่อพัฒนาแอปพลิเคชัน Hibernate ตัวอย่างที่ใช้การเชื่อมโยงแบบหนึ่งต่อกลุ่ม:

  • JDK 1.8 หรือใหม่กว่า
  • ไฮเบอร์เนต 5
  • Maven 3 หรือใหม่กว่า
  • ฐานข้อมูล H2

3. การตั้งค่า

3.1. การตั้งค่าฐานข้อมูล

ด้านล่างนี้คือสคริปต์ฐานข้อมูลของเราสำหรับตารางรถเข็นและรายการ เราใช้ข้อ จำกัด ของคีย์ภายนอกสำหรับการแมปแบบหนึ่งต่อหลาย :

CREATE TABLE `Cart` ( `cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`cart_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `Items` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `cart_id` int(11) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `cart_id` (`cart_id`), CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

การตั้งค่าฐานข้อมูลของเราพร้อมแล้วเรามาสร้างโครงการตัวอย่างไฮเบอร์เนตกันดีกว่า

3.2. การพึ่งพา Maven

จากนั้นเราจะเพิ่มการอ้างอิงไดรเวอร์ Hibernate และ H2 ลงในไฟล์pom.xmlของเรา การพึ่งพา Hibernate ใช้การบันทึก JBoss และจะถูกเพิ่มโดยอัตโนมัติเป็นการอ้างอิงแบบสกรรมกริยา:

  • ไฮเบอร์เนตเวอร์ชัน 5 .2.7 รอบชิงชนะเลิศ
  • ไดรเวอร์ H2 เวอร์ชัน1.4.197

โปรดไปที่ที่เก็บส่วนกลาง Maven สำหรับเวอร์ชันล่าสุดของ Hibernate และการอ้างอิง H2

3.3. การกำหนดค่าไฮเบอร์เนต

นี่คือการกำหนดค่าไฮเบอร์เนต:

  org.h2.Driver   jdbc:h2:mem:spring_hibernate_one_to_many sa org.hibernate.dialect.H2Dialect thread true  

3.4. HibernateAnnotationUtil Class

ด้วยคลาสHibernateAnnotationUtilเราเพียงแค่ต้องอ้างอิงไฟล์การกำหนดค่า Hibernate ใหม่:

private static SessionFactory sessionFactory; private SessionFactory buildSessionFactory() { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(). configure("hibernate-annotation.cfg.xml").build(); Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); return sessionFactory; } public SessionFactory getSessionFactory() { if(sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; }

4. โมเดล

การกำหนดค่าที่เกี่ยวข้องกับการทำแผนที่จะทำโดยใช้คำอธิบายประกอบ JPA ในคลาสโมเดล:

@Entity @Table(name="CART") public class Cart { //... @OneToMany(mappedBy="cart") private Set items; // getters and setters }

โปรดทราบว่าคำอธิบายประกอบ@OneToManyใช้เพื่อกำหนดคุณสมบัติในคลาสรายการที่จะใช้ในการแมปตัวแปรmappedBy นั่นคือเหตุผลที่เรามีทรัพย์สินชื่อ " รถเข็น " ในชั้นรายการ :

@Entity @Table(name="ITEMS") public class Items { //... @ManyToOne @JoinColumn(name="cart_id", nullable=false) private Cart cart; public Items() {} // getters and setters } 

สิ่งสำคัญที่ควรทราบคือคำอธิบายประกอบ@ManyToOneเชื่อมโยงกับตัวแปรคลาสCart คำอธิบายประกอบ@JoinColumnอ้างอิงคอลัมน์ที่แมป

5. ในการดำเนินการ

ในโปรแกรมทดสอบเรากำลังสร้างคลาสด้วยเมธอดmain () สำหรับรับ Hibernate Session และบันทึกโมเดลออบเจ็กต์ลงในฐานข้อมูลโดยใช้การเชื่อมโยงแบบหนึ่งต่อกลุ่ม:

sessionFactory = HibernateAnnotationUtil.getSessionFactory(); session = sessionFactory.getCurrentSession(); System.out.println("Session created"); tx = session.beginTransaction(); session.save(cart); session.save(item1); session.save(item2); tx.commit(); System.out.println("Cartitem1, Foreign Key Cartitem2, Foreign Key Cartmany-to-one">6. The @ManyToOne Annotation

As we have seen in section 2, we can specify a many-to-one relationship by using the @ManyToOne annotation. A many-to-one mapping means that many instances of this entity are mapped to one instance of another entity – many items in one cart.

The @ManyToOne annotation lets us create bidirectional relationships too. We'll cover this in detail in the next few subsections.

6.1. Inconsistencies and Ownership

Now, if Cart referenced Items, but Items didn't in turn reference Cart, our relationship would be unidirectional. The objects would also have a natural consistency.

In our case though, the relationship is bidirectional, bringing in the possibility of inconsistency.

Let's imagine a situation where a developer wants to add item1 to cart and item2 to cart2, but makes a mistake so that the references between cart2 and item2 become inconsistent:

Cart cart1 = new Cart(); Cart cart2 = new Cart(); Items item1 = new Items(cart1); Items item2 = new Items(cart2); Set itemsSet = new HashSet(); itemsSet.add(item1); itemsSet.add(item2); cart1.setItems(itemsSet); // wrong!

As shown above, item2 references cart2, whereas cart2 doesn't reference item2, and that's bad.

How should Hibernate save item2 to the database? Will item2 foreign key reference cart1 or cart2?

We resolve this ambiguity using the idea of an owning side of the relationship; references belonging to the owning side take precedence and are saved to the database.

6.2. Items as the Owning Side

As stated in the JPA specification under section 2.9, it's a good practice to mark many-to-one side as the owning side.

In other words, Items would be the owning side and Cart the inverse side, which is exactly what we did earlier.

So how did we achieve this?

By including the mappedBy attribute in the Cart class, we mark it as the inverse side.

At the same time, we also annotate the Items.cart field with @ManyToOne, making Items the owning side.

Going back to our “inconsistency” example, now Hibernate knows that the item2‘s reference is more important and will save item2‘s reference to the database.

Let's check the result:

item1 ID=1, Foreign Key Cart ID=1 item2 ID=2, Foreign Key Cart ID=2

Although cart references item2 in our snippet, item2‘s reference to cart2 is saved in the database.

6.3. Cart as the Owning Side

It's also possible to mark the one-to-many side as the owning side, and many-to-one side as the inverse side.

Although this is not a recommended practice, let's go ahead and give it a try.

The code snippet below shows the implementation of one-to-many side as the owning side:

public class ItemsOIO { // ... @ManyToOne @JoinColumn(name = "cart_id", insertable = false, updatable = false) private CartOIO cart; //.. } public class CartOIO { //.. @OneToMany @JoinColumn(name = "cart_id") // we need to duplicate the physical information private Set items; //.. } 

Notice how we removed the mappedBy element and set the many-to-one @JoinColumn as insertable and updatable to false.

If we run the same code, the result will be the opposite:

item1 ID=1, Foreign Key Cart ID=1 item2 ID=2, Foreign Key Cart ID=1

As shown above, now item2 belongs to cart.

7. Conclusion

We have seen how easy it is to implement the one-to-many relationship with the Hibernate ORM and H2 database using JPA annotations.

Additionally, we learned about bidirectional relationships and how to implement the notion of an owning side.

The source code in this article can be found over on GitHub.