為了追蹤hibernate的信息 <property name="hibernate.show_sql">true</property>
新建User類:
@Entity
@Table(name="E_USER",uniqueConstraints={
@UniqueConstraint(columnNames={"yahoo"})
})
public class User {
private int id;
private String yahoo; //昵稱唯一
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getYahoo() {
return yahoo;
}
public void setYahoo(String yahoo) {
this.yahoo = yahoo;
}
}
創建表 首先在hibernate.cfg.xml裡配置<mapping class="com.eric.po.User"/>說明:使用annoation同樣可以接受.hbm.XML文件
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,使用<property name="hbm2ddl.auto">create</property>屬性來自動創建
3,SchemaExport : new SchemaExport(new AnnotationConfiguration().configure()).create(true,true);
create(true,true):兩個參數:
Java代碼
* @param script print the DDL to the console
* @param export export the script to the database
hibernate建表語句:
drop table if exists E_USER
create table E_USER (id integer not null auto_increment, yahoo varchar(255), primary key (id), unique (yahoo))