摘要:此為我給公司內部新員工培訓的實戰演示例子,傻瓜級教程,講述了開發中的注意要點和常見錯誤,目的主要是讓他們適應企業級快速流水作業。由于是面對面講解,所以沒有詳細的文檔,現在簡單整理如下,希望對入門者有幫助。
培訓的目標:對下面的開發過程和模式快速理解和應用。基于我的UML架構-----〉Java POJOs代碼------〉在pojos中做xdoclet標識-------〉基于ant生成*.hbm.xml文件(借助于eclipse可以自動化配置)------〉生成database schma和數據庫sql語句。逐步可以讓新員工過渡到java5的annotation來開發EJB3 .
基于主鍵的一對一關聯映射
說明:下面是我們用到的例子,學生和自己學籍上的照片是一對一關系。下面是使用IBM RSA得到的一個模型,途中用的是兩個用途,表示的意思比較泛,最佳表示應該是一條無方向的線段,兩邊各標上1,代表一對一關系。(現在時間比較緊,所以沒來的急修改,這也是IBM反向工程的一個弱點,就好比目標是北京,但是現在目標指向了中國,不夠精確,但是可以反映這個意思)

下面是生成的數據庫E-R圖:

問題:初學者總是對pojos對象中的字段和數據庫中的字段做對比,對pojos對象中多出的propertity感到不解,其實這也是hibernate的關鍵所在,在那個表增加字段,增加外鍵,都是有規律的,也是完全符合數據庫的規則的,詳細看代碼.
初學者應該注意點,需要自己進行實踐的操作:
1,
/**
* @hibernate.class table = "image" schema = "hibernate_tutorial"
* @author Administrator
*
*/
schema
對
mysql
數據庫來說,是數據庫名字,這點注意
2,
你可以在關聯屬性上都定義外鍵,你看一下最后那邊的設置在數據庫
sql
語句中體現了,那個沒體現,我想你會有收獲的。
3,
/**
* @hibernate.one-to-one class = "com.javawebside.one2one.p1.Image"
* constrained = "false" outer-join = "true" cascade="all"
* @return Returns the image.
*/
注意cascade
的設置,如果沒有級聯,那么你可以最后
save student,
或者
save image
,或者,兩者都保存,你看一下數據庫中實際存入的數據,你一定會對
cascade
有更加深入的認識。
Image
類
package
com.javawebside.one2one.p1;
import java.sql.Blob;
/**
* @hibernate.class table = "image" schema = "hibernate_tutorial"
* @author Administrator
*
*/
public class Image {
private Long id;
private String name;
private Blob value = null;
/**
* @link association
*/
private Student student;
public Image(){}
public Image(Long id, String name, Blob value) {
super();
this.id = id;
this.name = name;
this.value = value;
}
/**
* @hibernate.id column = "id" generator-class = "foreign"
* @hibernate.generator-param name = "property" value = "student"
* @return Returns the id.
*/
public Long getId() {
return id;
}
/**
* @param id
* The id to set.
*/
public void setId(Long id) {
this.id = id;
}
/**
* @hibernate.property column = "name" not-null = "false" unique = "false"
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name
* The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @hibernate.property column = "value" not-null = "false" unique = "false"
* @return Returns the value.
*/
public Blob getValue() {
return value;
}
/**
* @param value
* The value to set.
*/
public void setValue(Blob value) {
this.value = value;
}
/**
* @hibernate.one-to-one class = "com.javawebside.one2one.p1.Student" constrained = "true"
* foreign-key="forein_key_name"
* @return
*/
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
Student
類
package
com.javawebside.one2one.p1;
/**
*
* @hibernate.class table = "student" schema = "hibernate_tutorial"
* @author Administrator
*
*/
public class Student {
private Long id;
private String name;
private String intro;
private Image image;
public Student() {
}
public Student(Long id, String name, String intro, Image image) {
super();
this.id = id;
this.name = name;
this.intro = intro;
this.image = image;
}
/**
* @hibernate.id column = "id" generator-class = "native"
* @return Returns the id.
*/
public Long getId() {
return id;
}
/**
* @param id
* The id to set.
*/
public void setId(Long id) {
this.id = id;
}
/**
* @hibernate.property column = "intro" not-null = "false" unique = "false"
* @return Returns the intro.
*/
public String getIntro() {
return intro;
}
/**
* @param intro
* The intro to set.
*/
public void setIntro(String intro) {
this.intro = intro;
}
/**
* @hibernate.property column = "name" not-null = "false" unique = "false"
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name
* The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @hibernate.one-to-one class = "com.javawebside.one2one.p1.Image"
* constrained = "false" outer-join = "true" cascade="all"
* @return Returns the image.
*/
public Image getImage() {
return image;
}
/**
* @param image
* The image to set.
*/
public void setImage(Image image) {
this.image = image;
}
}
下面是實際的操作類
BusinessService
類用于增加和刪除數據操作
package
com.javawebside.one2one.p1;
import java.sql.Blob;
import org.hibernate.*;
//import org.hibernate.cfg.Configuration;
//import java.util.*;
public class BusinessService {
private Session session;
public void setSession(Session se) {
session = se;
}
public Session getSession() {
return session;
}
public void saveStudent(Student Student) throws Exception {
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(Student);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public Student loadStudent(Long id) throws Exception {
Transaction tx = null;
try {
tx = session.beginTransaction();
Student Student = (Student) session.load(Student.class, id);
tx.commit();
return Student;
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public void printStudent(Student Student) throws Exception {
Image image = Student.getImage();
System.out.println("Image of " + Student.getName() + " is: "
+ image.getValue());
if (image.getStudent() == null)
System.out.println("Can not naviagte from Image to Student.");
}
public void test() throws Exception {
Student student = new Student();
Image image = new Image();
image.setName("
王東照片
"
);
student.setName("Tom");
student.setIntro("
王東
"
);
image.setStudent(student);
student.setImage(image);
saveStudent(student);
// student=loadStudent(student.getId());
// printStudent(student);
}
public static void main(String args[]) throws Exception {
BusinessService bs = new BusinessService();
bs.setSession(HibernateSessionFactory.currentSession());
if (bs.getSession() == null)
System.out.println("Session is null");
bs.test();
//bs.getSession().close();
}
}
hibernate
配置類
package
com.javawebside.one2one.p1;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "com/javawebside/one2one/p1/hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {
}
}