标签:
多对一关系实现起来不难,只需要在“多”的一方声明外键,声明外键在类的映射文件实现。
下面以老师学生为例,老师是1,学生是多
有一个有趣的地方,在Student类里面,没有声明teacherid这个属性,但是只要在配置文件声明了外键,那么就算类里面没有外键,配置文件的property也没有teacherid
下面是几个关键文件:
1、Student类(包含Student的增删改查)
package com.learn.po; import org.hibernate.Session; import org.hibernate.Transaction; import com.ehr.dao.HibernateUtil; public class Student { private int sid; public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } private String nm; private Teacher teacher; public String getNm() { return nm; } public void setNm(String nm) { this.nm = nm; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public static void addStudent(){ //这里的逻辑是,Teacher类的对象是Student的成员函数,向Student表插入数据的时候, //初始化Student,需要用Teacher对象,比如加小沈阳需要他的老师赵本上,所以先查找到赵本山,然后才能插入小沈阳, //至于外键,是Hibernate自动维护的 Session session = HibernateUtil.getSessionFactory().openSession(); Teacher t = (Teacher)session.get(Teacher.class, 2); Student s = new Student(); s.setNm("fanwei"); s.setTeacher(t); HibernateUtil.addObject(s); session.close(); } public static void getQuery(int id){ Session session = HibernateUtil.getSessionFactory().openSession(); Student s = (Student)session.get(Student.class, 1); /*找teacherid根本不进行查询,因为是外键,还在缓存存着*/ System.out.println(s.getTeacher().getTeacherid()); /*这里会在自动生成的Hibernate的sql语句会做内连接查询找到name*/ System.out.println(s.getTeacher().getNm()); } public static void changeTeacher(){ Session session = HibernateUtil.getSessionFactory().openSession(); Teacher t = (Teacher)session.get(Teacher.class, 3); Student s = (Student)session.get(Student.class, 1); s.setTeacher(t); session.beginTransaction().commit(); } public static void deleteStu(){ Session session = HibernateUtil.getSessionFactory().openSession(); Student s = new Student(); s.setSid(2); session.delete(s); session.beginTransaction().commit(); } public static void main(String[] args) { //addStudent(); //getQuery(1); //changeTeacher(); //deleteStu(); } }
<?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 package="com.learn.po"> <class name="Student" table="student" lazy="true"> <id name="sid" > <generator class="identity"></generator> </id> <property name="nm"></property> <many-to-one fetch="join" name="teacher" class="Teacher" column="teacherid"></many-to-one> </class> </hibernate-mapping>
package com.learn.po; import org.hibernate.Session; import com.ehr.dao.HibernateUtil; public class Teacher { private int teacherid; private String nm; public String getNm() { return nm; } public void setNm(String nm) { this.nm = nm; } public int getTeacherid() { return teacherid; } public void setTeacherid(int teacherid) { this.teacherid = teacherid; } public static void addTeacher(){ Teacher t = new Teacher(); t.setNm("te1"); //这里很神奇,是优Hibernate识别出来是什么类,然后插入相应的表 HibernateUtil.addObject(t); t.setNm("te2"); HibernateUtil.addObject(t); } public static void main(String args[]){ <pre name="code" class="java"><span style="white-space:pre"> </span>addTeacher();}}
<?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 package="com.learn.po"> <class name="Teacher" table="teacher" lazy="true"> <id name="teacherid"> <generator class="identity"></generator> </id> <property name="nm"></property> </class> </hibernate-mapping>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="foo"> <!-- 这个name没啥用 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 另外解释 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/testdb</property> <!-- url格式:mysql url+ 数据库名字--> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123</property> <!-- 用户名及密码 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- 下面指的是相应类配置文件,需要把。改为/ --> <mapping resource="com/learn/po/Teacher.hbm.xml"/> <mapping resource="com/learn/po/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
package com.ehr.dao; import java.io.Serializable; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.tool.hbm2ddl.SchemaExport; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure() .buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Serializable addObject(Object o) { // 获得session对象 Serializable s = null; Session session = HibernateUtil.getSessionFactory().openSession(); // 开启事务 Transaction tx = session.beginTransaction(); try { s = session.save(o);// 把对象保存到db,并且返回新建列的主键值 // 提交事务 tx.commit(); } catch (Exception e) { System.out.println(e.getMessage()); tx.rollback(); } finally { session.close(); } return s; } public static void main(String[] args) { Configuration cfg =new Configuration().configure(); SchemaExport e = new SchemaExport(cfg); e.create(true, true); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u011026968/article/details/47154059