Hibernate 再接触 多对一与一对多
多对一单向关联
数据库设计:
错误做法:在多方加外键
在多这一方加外键
第一种 annotation
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
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 //多对一,在多一方加外键 ,若想改名字就用joincolumn 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; } }
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> </class> </hibernate-mapping>
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> <many-to-one name="group" column="groupId" /> </class> </hibernate-mapping>
test
@Test public void testSchemaExport() { new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); }