一个用户组包含多个用户, 每个用户属于一个组.
一个人可以有多个车, 每个车属于一个人.
一个人有很多梦想, 一个特定的梦想属于一个人.
错误做法:
person里 有 personid, personname, dreamid
dream里有id, dreamdescr
会出现冗余, 因为是一对多
personid personname dreamid
1 zhangsan 1
1 zhangsan 2
dreamid dreamdescr
1 earn money
2 eat a lot
下面做人和组的关系, 一个group有很多user, 一个user只属于一个group, 所以group是 一 user是多
group.java:
package com.bjsxt.hibernate;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="t_group")public class Group { 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.java:
里面创建一个group对象, 是多对一的单项
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; private Group group; @ManyToOne public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @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:
com.mysql.jdbc.Driver jdbc:mysql://localhost/hibernate root linda0213 org.hibernate.dialect.MySQLDialect 1 thread org.hibernate.cache.NoCacheProvider true true
XML方式:
group是一, 不需要改什么:
user是多, 需要设置:
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(); }}