多对一关系
1.创建t_user表、t_group表
2.在eclipse中创建对应的实体类
1 package com.eneity; 2 3 public class User { 4 5 private int id; 6 private String name; 7 private Group group;//注意这里不是gid 而是group对象 8 9 public User() {10 super();11 // TODO Auto-generated constructor stub12 }13 public int getId() {14 return id;15 }16 public void setId(int id) {17 this.id = id;18 }19 public String getName() {20 return name;21 }22 public void setName(String name) {23 this.name = name;24 }25 public Group getGroup() {26 return group;27 }28 public void setGroup(Group group) {29 this.group = group;30 }31 32 33 }
1 package com.eneity; 2 3 public class Group { 4 5 private int id ; 6 private String name; 7 8 public Group() { 9 super();10 // TODO Auto-generated constructor stub11 }12 public int getId() {13 return id;14 }15 public void setId(int id) {16 this.id = id;17 }18 public String getName() {19 return name;20 }21 public void setName(String name) {22 this.name = name;23 }24 25 }
3.写对应的xml映射文件
注意:写好对应的xml文件后要在主配置文件中添加映射
1 2 4 56 7 188 119 10 12 1413 15 1716
1 2 4 56 7 158 119 10 12 1413
主配置文件
1 2 56 7 18com.mysql.jdbc.Driver 8xzt521 9jdbc:mysql://127.0.0.1:3306/myweb 10xzt 11 12true 13 14true 1516 17
4.写一个测试类
注意:如果只是要查询数据,只要开启session即可
要增删改的话,要开启事务管理
最后要提交事务(这样数据库中才会存进去数据)
关闭session
1 package com.test; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.Transaction; 6 import org.hibernate.cfg.Configuration; 7 import org.junit.After; 8 import org.junit.Before; 9 import org.junit.Test;10 11 import com.eneity.Customers;12 import com.eneity.Group;13 import com.eneity.Order;14 import com.eneity.User;15 16 17 public class Test1 {18 private SessionFactory buildSessionFactory;19 private Session Session;20 private Transaction Transaction;21 22 @Before23 public void before() {24 Configuration cfg = new Configuration().configure();25 buildSessionFactory = cfg.buildSessionFactory();26 Session = buildSessionFactory.openSession();27 Transaction = Session.beginTransaction();28 System.out.println(Session);29 30 31 }32 33 @Test34 public void test1() {35 // TODO Auto-generated method stub36 37 Group group = new Group();38 group.setName("duhao");39 User user = new User();40 user.setName("jiunan");41 user.setGroup(group);42 Session.save(group);43 Session.save(user);44 45 46 }47 48 @After49 public void after() {50 Transaction.commit();51 Session.close();52 53 }54 }