上篇博客已经采用jpa注解来实现了一对多关联映射,将这种关联映射以外键的形式处理,现在来看看怎么以第三张表的形式处理。采用jpa注解来映射数据库要使用的jar包见上篇博客:
一步步学习Hibernate框架(三):采用jpa实现一对多关联映射(一)
现在看第二种方式:以第三张表的关系来体现
Group.java
package com.tgb.zhudan; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="t_group") public class Group { private int id; private String name; private List<User> user; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany public List<User> getUser() { return user; } public void setUser(List<User> user) { this.user = user; } }
User.java
package com.tgb.zhudan; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="t_user") public class User { private int id; private String name; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_jpa_one2many</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <mapping class="com.tgb.zhudan.Group"/> <mapping class="com.tgb.zhudan.User"/> </session-factory> </hibernate-configuration>
ExportDB:
package com.tgb.zhudan; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; /** * 将hbm生成ddl * @author Administrator * */ public class ExportDB { public static void main(String[] args) { //默认读取hibernate.cfg.xml文件 Configuration cfg = new AnnotationConfiguration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true, true); } }
生成的数据库表如下:
t_user表:
t_group_t_user表:
总结:
从上面的三张图来看,在第三张表(t_group_t_user)中,将一端(t_group)中的id和多端(t_user)中的id拿出来作为第三张表的联合主键。这个关系由hebernate自己维护,不需要人为操作。