SSH學習四 Hibernate多對一的關係 + 增刪改查
阿新 • • 發佈:2019-01-25
多對一關係實現起來不難,只需要在“多”的一方宣告外來鍵,宣告外來鍵在類的對映檔案實現。
下面以老師學生為例,老師是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(); } }
2、Student的對映檔案
<?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>
3、Teacher的類
}}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();
4、Teacher的對映檔案
<?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>
5、Hibernate配置檔案
<!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>
6\HibernateUtil.java
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);
}
}