在1的方向加多的集合
Group.java
package com.bjsxt.hibernate; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="t_group") public class Group { private int id; private String name; private Set<User> users = new HashSet<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 @JoinColumn(name="groupId") //不写这句话会产生中间表 public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
package com.bjsxt.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; 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; } }
User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bjsxt.hibernate.User" table="t_user"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> </class> </hibernate-mapping>
Group.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bjsxt.hibernate.Group" table="t_group"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> <set name="users"> <key column="groupId"></key> <one-to-many class="com.bjsxt.hibernate.User"/> </set> </class> </hibernate-mapping>
@Test public void testSchemaExport() { new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); }
原文地址:https://www.cnblogs.com/frankzone/p/9599281.html
时间: 2024-11-05 09:04:14