Hibernate映射关系(一)

来源:互联网 发布:知天下资源吧 邀请码 编辑:程序博客网 时间:2024/05/02 02:47
本次测试的条件:
eclipse3.2+MyEclipse5.0+Sql server 2K
第一、在sql中建立两个表student,与course
student::字段为stuId,stuName,courseId
course:字段为courseId,courseName
两个表的DDL如下很简单:
create table "tytc"."dbo"."student"(
        "stuId" 
int not null,
       "stuName" 
char(10null,
       "courseId" 
int not null,
        
constraint "PK_student" primary key ("stuId")
    )

create table "tytc"."dbo"."course"(
        "courseId" 
int not null,
       "courseName" 
char(10null,
        
constraint "PK_course" primary key ("courseId")
    )
建立两表之间的关系:student中的courseId与course中的courseId
第二、利用MyEclipse中的工具自动生成映射文件,如下
Student.hbm.xml为:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<!-- 
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    
<class name="lcy.bo.Student" table="student" schema="dbo" catalog="tytc">
        
<id name="stuId" type="java.lang.Integer">
            
<column name="stuId" />
            
<generator class="assigned" />
        
</id>
        
<many-to-one name="course" class="lcy.bo.Course" fetch="select">
            
<column name="courseId" not-null="true" />
        
</many-to-one>
        
<property name="stuName" type="java.lang.String">
            
<column name="stuName" length="10" />
        
</property>
    
</class>
</hibernate-mapping>

Course.hbm.xml为:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<!-- 
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    
<class name="lcy.bo.Course" table="course" schema="dbo" catalog="tytc">
        
<id name="courseId" type="java.lang.Integer">
            
<column name="courseId" />
            
<generator class="assigned" />
        
</id>
        
<property name="courseName" type="java.lang.String">
            
<column name="courseName" length="10" />
        
</property>
        
<set name="students" inverse="true">
            
<key>
                
<column name="courseId" not-null="true" />
            
</key>
            
<one-to-many class="lcy.bo.Student" />
        
</set>
    
</class>
</hibernate-mapping>