基于XDoclet的Hibernate3企业级开发教程(1)——one2one映射类型的书写要点
 
摘要:此为我给公司内部新员工培训的实战演示例子,傻瓜级教程,讲述了开发中的注意要点和常见错误,目的主要是让他们适应企业级快速流水作业。由于是面对面讲解,所以没有详细的文档,现在简单整理如下,希望对入门者有帮助。
培训的目标:对下面的开发过程和模式快速理解和应用。基于我的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() {
    }
}
代码下载(包括每步的所有文件)