教程 > hibernate 教程 > 阅读:43

hibernate 映射文件——迹忆客-ag捕鱼王app官网

对象/关系映射通常在 xml 文档中定义。 这个映射文件指示 hibernate——如何将定义的一个或多个类映射到数据库表?

尽管许多 hibernate 用户选择手动编写 xml,但存在许多工具来生成映射文档。 其中包括适用于高级 hibernate 用户的 xdoclet、middlegen 和 andromda。

让我们考虑我们之前定义的 pojo 类,其对象将持久保存在下一节定义的表中。

public class employee {
   private int id;
   private string firstname; 
   private string lastname;   
   private int salary;  
   public employee() {}
   
   public employee(string fname, string lname, int salary) {
      this.firstname = fname;
      this.lastname = lname;
      this.salary = salary;
   }
   
   public int getid() {
      return id;
   }
   
   public void setid( int id ) {
      this.id = id;
   }
   
   public string getfirstname() {
      return firstname;
   }
   
   public void setfirstname( string first_name ) {
      this.firstname = first_name;
   }
   
   public string getlastname() {
      return lastname;
   }
   
   public void setlastname( string last_name ) {
      this.lastname = last_name;
   }
   
   public int getsalary() {
      return salary;
   }
   
   public void setsalary( int salary ) {
      this.salary = salary;
   }
}

我们愿意提供持久性的每个对象都会对应一个表。 考虑上述对象需要存储和检索到以下 rdbms 表中

create table employee (
   id int not null auto_increment,
   first_name varchar(20) default null,
   last_name  varchar(20) default null,
   salary     int  default null,
   primary key (id)
);

基于以上两个实体,我们可以定义如下映射文件,它指示 hibernate 如何将定义的一个或多个类映射到数据库表。

?xml version = "1.0" encoding = "utf-8"?>
 

   
      
      
         this class contains the employee detail. 
      
      
      
         
      
      
      
      
      
      
   

我们应该将映射文档保存在格式为 .hbm.xml 的文件中。 我们将映射文档保存在文件 employee.hbm.xml 中。

让我们看看了解一下关于映射文件中使用的映射元素的一些细节

  • 映射文档是以 作为根元素的 xml 文档,它包含所有 元素。
  • 元素用于定义从 java 类到数据库表的特定映射。 java 类名使用 class 元素的 name 属性指定,数据库表名使用 table 属性指定。
  • 元素是可选元素,可用于创建类描述。
  • 元素将类中的唯一 id 属性映射到数据库表的主键。 id 元素的 name 属性指的是类中的属性,column 属性指的是数据库表中的列。 type 属性保存hibernate 映射类型,这种映射类型将从java 转换为sql 数据类型。
  • id 元素中的 元素用于自动生成主键值。生成器元素的 class 属性设置为 native 来让 hibernate 选择身份、序列或 hilo 算法来根据底层数据库的功能创建主键。
  • 元素用于将 java 类属性映射到数据库表中的列。元素的名称属性是指类中的属性,列属性是指数据库表中的列。 type 属性保存hibernate 映射类型,这种映射类型将从java 转换为sql 数据类型。

还有其他可用的属性和元素,它们将在映射文档中使用,在讨论其他 hibernate 相关主题时,将尝试涵盖尽可能多的内容。

查看笔记

扫码一下
查看教程更方便
网站地图