Category类
@Table(name="jpa_categories") @Entity public class Category { @GeneratedValue @Id private Integer id; @Column(name="category_name") private String categoryName; @ManyToMany(mappedBy="categories") private Set<Item> items = new HashSet<>(); //getter setter }
Item类
@Table(name="jpa_items") @Entity public class Item { @GeneratedValue @Id private Integer id; @Column(name="item_name") private String itemName; //中间表,name为中间表的表名,joinColumns当前类在中间表中的外键(name为外键的列名,referencedColumnName当前表的哪一列), //inverseJoinColumns映射关联的类所在中间表的外键 @JoinTable(name="item_category", joinColumns={@JoinColumn(name="item_id", referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="category_id", referencedColumnName="id")}) @ManyToMany private Set<Category> categories = new HashSet<>(); //getter setter }
测试保存
@Test public void testManyToManyPersistance() { Item item1 = new Item(); item1.setItemName("item1"); Item item2 = new Item(); item2.setItemName("item2"); Category category1 = new Category(); category1.setCategoryName("category1"); Category category2 = new Category(); category2.setCategoryName("category2"); item1.getCategories().add(category1); item1.getCategories().add(category2); item2.getCategories().add(category1); item2.getCategories().add(category2); category1.getItems().add(item1); category1.getItems().add(item2); category2.getItems().add(item1); category2.getItems().add(item2); entityManager.persist(item1); entityManager.persist(item2); entityManager.persist(category1); entityManager.persist(category2); }
保存结果如下图
测试select
//默认使用懒加载策略 //无论先使用维护关联关系的一方获取还是使用不维护关联关系的一方获取,SQL相同 @Test public void testManyToManyFind() { // Item item = entityManager.find(Item.class, 1); // System.out.println(item.getItemName()); // System.out.println(item.getCategories().size()); //上下两种方式SQL语句相同 Category category = entityManager.find(Category.class, 1); System.out.println(category.getCategoryName()); System.out.println(category.getItems().size()); }
时间: 2024-10-09 08:30:29