Hibernate自动创建表的两种方式(第二种方法)(转) 第二种方法 首先: 1.创建学生类 package com.day02; public class Student { private int id;//定义成整形,但也可定义成字符串,但字符串有时不行,好奇怪。还是定义成整形。 private String name; private int age; private String address; public Student(){} public Student(int id, String name, int age, String address) { super(); this.id = id; this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } } 2.写配置文件 <?xml version="1.0"?><hibernate-mapping package="com.day02"><class name="Student" table="Student"><id name="id" column="oid"><generator class="native"></generator></id><property name="name" column="t_name"></property><property name="age" column="t_age"></property><property name="address" column="t_address"></property></class></hibernate-mapping> 3.配置hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8'?><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="connection.username">root</property><property name="connection.url">jdbc:mysql://127.0.0.1/xiaogu</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property><property name="connection.password">root</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><mapping resource="com/day02/Student.hbm.xml"></mapping><mapping resource="com/day02/Account.hbm.xml"></mapping></session-factory></hibernate-configuration> 4.定义工具类 package com.day02; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HbnUtil { private static SessionFactory sf; static{ Configuration conf = new Configuration().configure("hibernate.cfg.xml"); SchemaExport dbExport = new SchemaExport(conf); // dbExport.setOutputFile("d:/cxsql.txt");//首先在d盘创建一个叫cxsql.txt的空文档,程序会把生成的sql语句输出 dbExport.create(true, true); sf=conf.buildSessionFactory(); } public static Session getSession(){ return sf.openSession(); } public static void closeSessionFactory(){ if(!sf.isClosed()){ sf.close(); } } } 5.写测试类 package com.day02; import org.hibernate.Session; public class Test { public static void main(String[] args) { Student stu=new Student(); stu.setAddress("hebei"); stu.setAge(23); stu.setName("xiaogu"); Session session=HbnUtil.getSession(); session.beginTransaction(); session.save(stu); session.getTransaction().commit(); session.close(); } }