[Java教程]多对一的单向关联
0
2017-04-20 00:01:38
多对一与一对多
1.多对一单向关联
a) 项目名称:
b) 数据库表设计:在多方加外键
c) annotation:@Many2One
d)
多对一:从多配置到一
案例:一个组(Group)有多个用户(User),配置从User到Group的多对一的单向关联
Annotation:
Group类:1 package com.bjsxt.hibernate; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.persistence.Table; 7 8 @Entity 9 @Table(name="t_group")10 public class Group {11 private Integer id;12 13 private String name;14 15 @Id16 @GeneratedValue17 public Integer getId() {18 return id;19 }20 21 public void setId(Integer id) {22 this.id = id;23 }24 25 public String getName() {26 return name;27 }28 29 public void setName(String name) {30 this.name = name;31 }32 }
User 类:1 package com.bjsxt.hibernate; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.persistence.JoinColumn; 7 import javax.persistence.ManyToOne; 8 import javax.persistence.Table; 9 10 @Entity11 @Table(name="t_user")12 public class User {13 private Integer id;14 15 private String name;16 17 private Group group;18 19 @Id20 @GeneratedValue21 public Integer getId() {22 return id;23 }24 25 public void setId(Integer id) {26 this.id = id;27 }28 29 public String getName() {30 return name;31 }32 33 public void setName(String name) {34 this.name = name;35 }36 37 @ManyToOne38 @JoinColumn(name="groupId")//设置列的名称,可以不写,默认为group_id39 public Group getGroup() {40 return group;41 }42 43 public void setGroup(Group group) {44 this.group = group;45 }46 }
Group:
1 package com.bjsxt.hibernate; 2 3 public class Group { 4 private Integer id; 5 6 private String name; 7 8 public Integer getId() { 9 return id;10 }11 12 public void setId(Integer id) {13 this.id = id;14 }15 16 public String getName() {17 return name;18 }19 20 public void setName(String name) {21 this.name = name;22 }23 }
View Code
Group.hbm.1 2 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 7 8 9 10 11 12 13
User:
1 package com.bjsxt.hibernate; 2 3 public class User { 4 private Integer id; 5 6 private String name; 7 8 private Group group; 9 10 public Integer getId() {11 return id;12 }13 14 public void setId(Integer id) {15 this.id = id;16 }17 18 public String getName() {19 return name;20 }21 22 public void setName(String name) {23 this.name = name;24 }25 26 public Group getGroup() {27 return group;28 }29 30 public void setGroup(Group group) {31 this.group = group;32 }33 }
View Code
User.hbm.1 2 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 7 8 9 10 11 12 13 14
上面两种配置的效果一样:
jar包链接: https://pan.baidu.com/s/1qY356PY 密码: bm8f
代码链接: https://pan.baidu.com/s/1o7F4HIE 密码: ap4m
本文网址:http://www.shaoqun.com/a/307412.html
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。
0