博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hibernate,JPA注解@ManyToMany_JoinTable
阅读量:5104 次
发布时间:2019-06-13

本文共 11095 字,大约阅读时间需要 36 分钟。

可以通过@ManyToMany注解可定义的多对多关联。同时,也需要通过注解@JoinTable描述关联表和关联条件。如果是双向关联,其中一段必须定义为owner,另一端必须定义为inverse(在对关联表进行更新操作时这一端将被忽略)。被关联端不必也不能描述物理映射: 只需要一个简单的mappedBy参数,该参数包含了主体端的属性名,这样就绑定双方的关系。

用例代码如下:

  • 数据库DDL语句

1,CAT表

1 create table CAT 2 ( 3   id          VARCHAR2(32 CHAR) not null, 4   create_time TIMESTAMP(6) default sysdate, 5   update_time TIMESTAMP(6), 6   cat_name    VARCHAR2(255 CHAR), 7   first_name  VARCHAR2(255 CHAR), 8   last_name   VARCHAR2(255 CHAR), 9   version     NUMBER(10) not null10 )

2,HOBBY表

1 create table HOBBY2 (3   id          VARCHAR2(32 CHAR) not null,4   create_time TIMESTAMP(6),5   update_time TIMESTAMP(6),6   name        VARCHAR2(255 CHAR),7   cat_id      VARCHAR2(32 CHAR)8 )
  • hibernate.cfg.xml
1 
2 5
6
7
8
org.hibernate.dialect.Oracle10gDialect
9
oracle.jdbc.OracleDriver
10
jdbc:oracle:thin:@127.0.0.1:1521:orcl
11
wxuatuser
12
xlh
13
true
14
15
update
16
17 18
19
20 21
22
  • java类

实体类 - 基类 

1 package model; 2 import java.io.Serializable; 3 import java.util.Date; 4 import javax.persistence.Column; 5 import javax.persistence.GeneratedValue; 6 import javax.persistence.Id; 7 import javax.persistence.MappedSuperclass; 8 import org.hibernate.annotations.GenericGenerator; 9 /**10  * 实体类 - 基类11  */12 @MappedSuperclass13 public class BaseEntity implements Serializable {14 15     private static final long serialVersionUID = -6718838800112233445L;16 17     private String id;// ID18     private Date create_time;// 创建日期19     private Date update_time;// 修改日期20     @Id21     @Column(length = 32, nullable = true)22     @GeneratedValue(generator = "uuid")23     @GenericGenerator(name = "uuid", strategy = "uuid")24     public String getId() {25         return id;26     }27     public void setId(String id) {28         this.id = id;29     }30     @Column(updatable = false)31     public Date getCreate_time() {32         return create_time;33     }34     public void setCreate_time(Date create_time) {35         this.create_time = create_time;36     }37     public Date getUpdate_time() {38         return update_time;39     }40     public void setUpdate_time(Date update_time) {41         this.update_time = update_time;42     }43     @Override44     public int hashCode() {45         return id == null ? System.identityHashCode(this) : id.hashCode();46     }47     @Override48     public boolean equals(Object obj) {49         if (this == obj) {50             return true;51         }52         if (obj == null) {53             return false;54         }55         if (getClass().getPackage() != obj.getClass().getPackage()) {56             return false;57         }58         final BaseEntity other = (BaseEntity) obj;59         if (id == null) {60             if (other.getId() != null) {61                 return false;62             }63         } else if (!id.equals(other.getId())) {64             return false;65         }66         return true;67     }68 }

实体类

 Cat.java

1 package b12_ManyToMany_JoinTable; 2 import java.util.Set; 3 import javax.persistence.AttributeOverride; 4 import javax.persistence.AttributeOverrides; 5 import javax.persistence.Column; 6 import javax.persistence.Embedded; 7 import javax.persistence.Entity; 8 import javax.persistence.FetchType; 9 import javax.persistence.JoinColumn;10 import javax.persistence.JoinTable;11 import javax.persistence.ManyToMany;12 import javax.persistence.Version;13 import model.BaseEntity;14 import org.hibernate.annotations.Cascade;15 import org.hibernate.annotations.DynamicInsert;16 import org.hibernate.annotations.DynamicUpdate;17 18 @Entity19 @DynamicInsert20 @DynamicUpdate21 public class Cat extends BaseEntity{22     /**23      * 实体类24      */25     private static final long serialVersionUID = -2776330321385582872L;26     27     private String cat_name;28     private Name name;29     private int version;30     31     private Set
hobby;32 33 @ManyToMany(fetch = FetchType.EAGER)34 @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})35 @JoinTable(name = "CAT_HOBBY", 36 joinColumns = { @JoinColumn(name = "CAT_ID") },37 inverseJoinColumns = { @JoinColumn(name = "HOBBY_ID") })38 public Set
getHobby() {39 return hobby;40 }41 42 public void setHobby(Set
hobby) {43 this.hobby = hobby;44 } 45 @Version46 public int getVersion() {47 return version;48 }49 50 public void setVersion(int version) {51 this.version = version;52 }53 54 public String getCat_name() {55 return cat_name;56 }57 58 public void setCat_name(String cat_name) {59 this.cat_name = cat_name;60 }61 62 @Embedded63 @AttributeOverrides({64 @AttributeOverride(name = "first_name", column = @Column(name = "first_name")),65 @AttributeOverride(name = "last_name", column = @Column(name = "last_name")) })66 public Name getName() {67 return name;68 }69 70 public void setName(Name name) {71 this.name = name;72 } 73 }

Hobby.java

1 package b12_ManyToMany_JoinTable; 2 import java.util.Set; 3 import javax.persistence.Entity; 4 import javax.persistence.FetchType; 5 import javax.persistence.ManyToMany; 6 import model.BaseEntity; 7  8 @Entity 9 public class Hobby extends BaseEntity {10     /**11      * 实体类12      */13     private static final long serialVersionUID = 4921844599282935594L;14     15     private String name;16     private Set
cat;17 18 @ManyToMany(mappedBy = "hobby",fetch=FetchType.LAZY)19 public Set
getCat() {20 return cat;21 }22 public void setCat(Set
cat) {23 this.cat = cat;24 }25 26 public String getName() {27 return name;28 }29 public void setName(String name) {30 this.name = name;31 }32 }

组件类

1 package b12_ManyToMany_JoinTable; 2 import java.io.Serializable; 3 import javax.persistence.Embeddable; 4  5 @Embeddable 6 public class Name implements Serializable { 7     /** 8      * 嵌入式组建 9      */10     private static final long serialVersionUID = -2776330321385582872L;11     12     private String first_name;13     private String last_name;14     public String getFirst_name() {15         return first_name;16     }17     public void setFirst_name(String first_name) {18         this.first_name = first_name;19     }20     public String getLast_name() {21         return last_name;22     }23     public void setLast_name(String last_name) {24         this.last_name = last_name;25     }    26 }

Dao

1 package daoUtil; 2 import org.hibernate.HibernateException; 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.Transaction; 6 import org.hibernate.cfg.Configuration; 7 import org.hibernate.service.ServiceRegistry; 8 import org.hibernate.service.ServiceRegistryBuilder; 9 10 public class HibernateUtil {11 12     private static final SessionFactory sessionFactory;13 14     static {15         try {16             Configuration cfg = new Configuration().configure();17             ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()18                     .applySettings(cfg.getProperties()).buildServiceRegistry();19             sessionFactory = cfg.buildSessionFactory(serviceRegistry);20         } catch (Throwable ex) {21             throw new ExceptionInInitializerError(ex);22         }23     }24 25     public static Session getSession() throws HibernateException {26         return sessionFactory.openSession();27     }28 29     public static Object save(Object obj){30         Session session = HibernateUtil.getSession();31         Transaction tx = null;32         try {33             tx = session.beginTransaction();34             session.save(obj);35             tx.commit();36         } catch (RuntimeException e) {37             if (tx != null) {38                 tx.rollback();39             }40             throw e;41         } finally {42             session.close();43         }44         return obj;45     }46     47     public static void delete(Class
clazz,String id){48 Session session = HibernateUtil.getSession();49 Transaction tx = null;50 try {51 tx = session.beginTransaction();52 Object obj = session.get(clazz,id);53 session.delete(obj);54 tx.commit();55 } catch (RuntimeException e) {56 if (tx != null) {57 tx.rollback();58 }59 throw e;60 } finally {61 session.close();62 }63 }64 }

main

1 package b12_ManyToMany_JoinTable; 2 import java.util.HashSet; 3 import java.util.Set; 4 import daoUtil.HibernateUtil; 5  6 public class Test_ManyToMany_JoinTable { 7  8     private Cat save(){ 9         Cat cat1 = new Cat();10         Cat cat2 = new Cat();11         cat1.setCat_name("b12_ManyToMany_JoinTable1");12         cat2.setCat_name("b12_ManyToMany_JoinTable2");13 14         Set
hobbies = new HashSet
();15 Hobby hobby1 = new Hobby();16 hobby1.setName("乒乓球");17 hobbies.add(hobby1);18 19 Hobby hobby2 = new Hobby();20 hobby2.setName("冰球");21 hobbies.add(hobby2);22 23 cat1.setHobby(hobbies);24 cat2.setHobby(hobbies);25 26 HibernateUtil.save(cat1);27 HibernateUtil.save(cat2);28 System.out.println(cat1.getId());29 System.out.println(cat2.getId());30 return cat1;31 }32 33 public static void main(String[] args) {34 // 通过cat加载hobby35 Cat cat = new Test_ManyToMany_JoinTable().save();36 37 // Cat cat1 = (Cat)HibernateUtil.getSession().get(Cat.class, "8a6cc5a34c77d08f014c77d0a0490003");38 // System.out.println(cat1.getId());39 // 40 // Set
hobbies = cat1.getHobby();41 // for (Hobby hobby : hobbies) {42 // System.out.println(hobby.getName());43 // }44 // 45 // // delete46 // HibernateUtil.delete(Cat.class, "8a6cc5a34c77d08f014c77d0a0490003");47 48 // 通过hobby加载cat49 // Hobby hobby = (Hobby)HibernateUtil.getSession().get(Hobby.class, "8a6cc5a34c77d08f014c77d09fbb0001");50 // System.out.println(hobby.getId());51 // 52 // Set
cats = hobby.getCat();53 // for (Cat cat : cats) {54 // System.out.println(cat.getCat_name());55 // }56 }57 }

 

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:http://files.cnblogs.com/files/xiluhua/hibernate%40ManyToMany_JoinTable.rar

 

转载于:https://www.cnblogs.com/xiluhua/p/4386045.html

你可能感兴趣的文章
北漂周记--第5记--拼命编程
查看>>
比赛总结一
查看>>
SpringBoot项目打包
查看>>
JSP的3种方式实现radio ,checkBox,select的默认选择值
查看>>
Linux操作系统 和 Windows操作系统 的区别
查看>>
《QQ欢乐斗地主》山寨版
查看>>
文件流的使用以及序列化和反序列化的方法使用
查看>>
Android-多线程AsyncTask
查看>>
第一个Spring冲刺周期团队进展报告
查看>>
C++函数基础知识
查看>>
红黑树 c++ 实现
查看>>
Android 获取网络链接类型
查看>>
报表服务框架:WEB前端UI
查看>>
5.9UDP客户端服务器-基于OK6410
查看>>
java自学基础、项目实战网站推荐
查看>>
软件包的使用
查看>>
linux中启动与终止lnmp的脚本
查看>>
BZOJ 1304: [CQOI2009]叶子的染色
查看>>
gdb中信号的处理[转]
查看>>
学习Javascript闭包(Closure)
查看>>