Hibernate Tutorial Anotasi Satu hingga Banyak

1. Pengenalan

Tutorial Hibernate cepat ini akan membawa kita melalui contoh pemetaan satu-ke-banyak menggunakan anotasi JPA, alternatif kepada XML.

Kami juga akan mengetahui apa hubungan dua arah, bagaimana mereka dapat mewujudkan ketidakkonsistenan, dan bagaimana idea pemilikan dapat membantu.

2. Penerangan

Ringkasnya, pemetaan satu-ke-banyak bermaksud bahawa satu baris dalam tabel dipetakan ke beberapa baris di meja lain.

Mari lihat rajah hubungan entiti berikut untuk melihat perkaitan satu-ke-banyak :

Untuk contoh ini, kami akan melaksanakan sistem troli di mana kami mempunyai jadual untuk setiap troli dan satu lagi jadual untuk setiap item. Satu troli boleh mempunyai banyak item, jadi di sini kita mempunyai pemetaan satu-ke-banyak .

Cara ini berfungsi di peringkat pangkalan data adalah kita mempunyai cart_id sebagai kunci utama dalam jadual troli dan juga cart_id sebagai kunci asing dalam item .

Cara kami melakukannya dalam kod adalah dengan @OneToMany .

Mari memetakan kelas Troli ke objek Item dengan cara yang mencerminkan hubungan dalam pangkalan data:

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

Kami juga dapat menambahkan rujukan ke Keranjang di Item menggunakan @ManyToOne , menjadikan ini hubungan dua arah. Dua arah bermaksud bahawa kita dapat mengakses item dari troli , dan juga kereta dari item .

Harta mappedBy adalah yang kami gunakan untuk memberitahu Hibernate pemboleh ubah yang kami gunakan untuk mewakili kelas induk di kelas anak kami.

Teknologi dan perpustakaan berikut digunakan untuk mengembangkan contoh aplikasi Hibernate yang menerapkan hubungan satu-ke-banyak :

  • JDK 1.8 atau lebih baru
  • Hibernate 5
  • Maven 3 atau lebih baru
  • Pangkalan data H2

3. Persediaan

3.1. Penyediaan Pangkalan Data

Berikut adalah skrip pangkalan data kami untuk jadual Keranjang dan Item . Kami menggunakan kekangan kunci asing untuk pemetaan satu-ke-banyak :

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;

Penyediaan pangkalan data kami sudah siap, jadi mari kita teruskan untuk membuat projek contoh Hibernate.

3.2. Ketergantungan Maven

Kami kemudian akan menambahkan kebergantungan pemacu Hibernate dan H2 ke fail pom.xml kami . Ketergantungan Hibernate menggunakan pembalakan JBoss, dan secara automatik ia ditambahkan sebagai pergantungan transitif:

  • Hibernate versi 5 .2.7.Final
  • Pemacu H2 versi 1 .4.197

Sila kunjungi repositori pusat Maven untuk versi terkini Hibernate dan dependensi H2.

3.3. Konfigurasi Hibernate

Berikut adalah konfigurasi Hibernate:

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

3.4. HibernateAnnotationUtil Class

Dengan kelas HibernateAnnotationUtil , kita hanya perlu merujuk fail konfigurasi Hibernate yang baru:

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. Model

Konfigurasi pemetaan yang berkaitan akan dilakukan dengan menggunakan anotasi JPA di kelas model:

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

Harap maklum bahawa anotasi @OneToMany digunakan untuk menentukan harta di kelas Item yang akan digunakan untuk memetakan pemboleh ubah mappedBy . Itulah sebabnya kami mempunyai harta bernama " troli " di kelas Item :

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

Penting juga untuk diperhatikan bahawa anotasi @ManyToOne dikaitkan dengan pemboleh ubah kelas Cart . Anotasi @JoinColumn merujuk pada lajur yang dipetakan.

5. Dalam Tindakan

Dalam program ujian, kami membuat kelas dengan kaedah utama () untuk mendapatkan Sesi Hibernate, dan menyimpan objek model ke dalam pangkalan data yang melaksanakan persatuan satu-ke-banyak :

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.