Hibernate 一对一关联 映射配置

最近做项目,用到hibernate框架.. 项目架构为Spring2.5+Hibernate 3.32+JSF +OS Workflow 整合的一个框架..

本来是Ibatis框架做, 因为OS Workflow工作流 官方 只整合 Hibernate框架的实现,没有与ibatis框架.进行整合.

只能用Hibernate了.. 好久没用这个Hibernate了.感觉都有点生疏..

下面写一个one to one的实例来巩固一下以前学习的知识:

User Model 类如下:

public class User implements java.io.Serializable {
	 private Integer id;
	 private String username;
	 private String password;
	 private String email;
	 private String course;
	 private Course mycourse;
 
   // Constructors
	 public Course getMycourse(){
	     return this.mycourse;  
	 }
	 
	 public void setMycourse(Course cc){
	     this.mycourse=cc;
 	 }
 	 
 	/** default constructor */
	 public User() {
	 
	 } 
	 
	 public User(Integer id, String username, String password, String email,String course) {
		  this.id = id;
		  this.username = username;
		  this.password = password;
		  this.email = email;
		  this.course = course;
	 }
}

 Course  Model 如下:

public class Course  implements java.io.Serializable {
     private Integer id;
     private String english;
     private String math;
     private String music;
     private String jsp;
     private String java;
     private User myuser;
     
    // Constructors
    public User getMyuser() {
    	return myuser;
    }
 
	  public void setMyuser(User myuser) {
	  	this.myuser = myuser;
	  }
	 
		 public Course() {
		 
		 } 
	 //getter 和  setter方法省略.
}

接下来,就是配置Hibernate 映射文件了.

1.User.hbm.xml代码

<hibernate-mapping>
    <class name="pack.java.demo.User" table="user" catalog="myproject" lazy="true">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment" />
        </id>
                <one-to-one name="mycourse" class="Course" 
                    fetch="join" cascade="all"  />
    </class>
</hibernate-mapping>

2.Course.hbm.xml代码如下:

<hibernate-mapping>
    <class name="pack.java.demo.Course" table="course" catalog="myproject" >
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="foreign" >
            <param name="property">myuser</param>
            </generator>
        </id>
        <property name="english" type="java.lang.String">
            <column name="english" length="24" />
        </property>
        <property name="math" type="java.lang.String">
            <column name="math" length="24" />
        </property>
        <property name="music" type="java.lang.String">
            <column name="music" length="24" />
        </property>
        <property name="jsp" type="java.lang.String">
            <column name="jsp" length="24" />
        </property>
        <property name="java" type="java.lang.String">
            <column name="java" length="24" />
        </property>     
        <one-to-one name="myuser" class="User" constrained="true"></one-to-one>
    </class>
</hibernate-mapping>

简单的一对一 映射文件就配置好了..接下来就是写方法,测试..

相关推荐