多对一是在多的类上存在一的对象
一对多是在一的类上存在多的集合.
多的类
user.java:
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; }}
一的类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 Setusers = new HashSet (); @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 getUsers() { return users; } public void setUsers(Set users) { this.users = users; }}
test文件:
package com.bjsxt.hibernate;import java.util.Date;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;public class HibernateORMappingTest { private static SessionFactory sessionFactory; //@BeforeClass public static void beforeClass() { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } //@AfterClass public static void afterClass() { sessionFactory.close(); } @Test public void testSchemaExport() { new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); } public static void main(String[] args) { beforeClass(); }}
运行test的结果:
14:15:34,169 DEBUG org.hibernate.tool.hbm2ddl.SchemaExport:303 - create table t_group ( id integer not null auto_increment, name varchar(255), primary key (id) )14:15:34,304 DEBUG org.hibernate.tool.hbm2ddl.SchemaExport:303 - create table t_user ( id integer not null auto_increment, name varchar(255), groupId integer, primary key (id) )14:15:34,409 DEBUG org.hibernate.tool.hbm2ddl.SchemaExport:303 - alter table t_user add index FKCB63CCB6C3D18669 (groupId), add constraint FKCB63CCB6C3D18669 foreign key (groupId) references t_group (id)14:15:34,674 INFO org.hibernate.tool.hbm2ddl.SchemaExport:196 - schema export complete
XML方式:
作为多的一方user正常写成:
一的一方 group需要写set: