首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate 註解教程(二):表結構自動生成與映射

     編輯:Java 相關知識

開啟 SQL 顯示

<property name="hibernate.show_sql">true</property>

實體類定義

@Entity
@Table(name="E_USER", uniqueConstraints={@UniqueConstraint(columnNames={"yahoo"})})
public class User {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String yahoo;
    // getter/setter
}

三種建表方式

1. 手動建表

DROP TABLE IF EXISTS `e_user`;
CREATE TABLE `e_user` (
  `id` int(11) NOT NULL auto_increment,
  `yahoo` varchar(255) default NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `yahoo` (`yahoo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. hbm2ddl.auto 自動建表

<property name="hbm2ddl.auto">create</property>

3. SchemaExport 程序化建表

new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);

參數:script(打印 DDL)、export(執行建表)。

Hibernate 生成 DDL

drop table if exists E_USER
create table E_USER (
    id integer not null auto_increment,
    yahoo varchar(255),
    primary key (id),
    unique (yahoo)
)

註解

AnnotationConfiguration 同樣支持 .hbm.xml 混合映射文件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved