由于hibernate3提供了自带的工具hbm2ddl,建立根据你的对象建立数据库是一件非常简单的事情。
Demo结构图如下:
1、首先建立POJO类
1package org.apple.hibernate;23public class User {4 private String id;5 private String name;6 private String password;7 public String getId() {8 return id;9 }10 public void setId(String id) {11 this.id = id;12 }13 public String getName() {14 return name;15 }16 public void setName(String name) {17 this.name = name;18 }19 public String getPassword() {20 return password;21 }22 public void setPassword(String password) {23 this.password = password;24 }2526}
2、根据POJO类里面里面相关的字段写User.hbm.xml映射文件
1234 5 6 7 8 910 11 12 13 14
3、建立hibernate.cfg.xml
1456 78 org.hibernate.dialect.MySQLDialect9 true10 11 12
4、建立 hibernate.properties数据库链接
## 数据库链接,密码自己根据自己的实际数据库进行修改!
hibernate.dialect org.hibernate.dialect.MySQLDialecthibernate.connection.driver_class com.mysql.jdbc.Driverhibernate.connection.url jdbc:mysql://localhost/usertest?useUnicode=true&characterEncoding=GBKhibernate.connection.username roothibernate.connection.password password
5、建立UserTest类
1package org.apple.hibernate;23import org.hibernate.cfg.Configuration;4import org.hibernate.tool.hbm2ddl.SchemaExport;5678class UserTest{9 public static void main(String[] args) throws Exception{10 //配置环境,分析xml映射文件11 Configuration conf= new Configuration()12 .addClass(User.class);1314 //生成并输出sql到文件(当前目录)和数据库15 SchemaExport dbExport=new SchemaExport(conf);16 dbExport.create(true, true);17 }18}
6、建立log4j.properties日志文件
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
PS:要在mysql数据库里面先建立好usertest表,然后运行UserTest类,这样就可以顺利通过hibernate3提供了自带的工具hbm2ddl,建立根据你的对象建立数据库相关表。
打开mysql数据库:
大功告成!