日期:2014-05-16 浏览次数:20505 次
配置文件 hibernate.cfg.xml[放到src目录下]
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <!--Examda提示:数据库用户名--> <property name="connection.username">root</property> <!--数据库URL--> <property name="connection.url"> jdbc:mysql://192.168.1.102:3306/sms?useUnicode=true&characterEncoding=utf8 </property> <!--dialect,每个数据库对应的Dialet匹配其平台特性--> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <!--数据库密码--> <property name="connection.password">root</property> <!--数据库驱动--> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <!--是否将运行产生的sql语句输出到日志--> <property name="hibernate.show_sql">True</property> <!--Examda,是否使用数据库外连接--> <property name="hibernate.use_out_join">True</property> <!--映射类的xml文件--> <mapping resource="cn/com/swansoft/sms/dao/pojo/Sms.hbm.xml" /> <mapping resource="cn/com/swansoft/sms/dao/pojo/SmsUser.hbm.xml" /> <mapping resource="cn/com/swansoft/sms/dao/pojo/SmsTemplate.hbm.xml"/> </session-factory> </hibernate-configuration>
Java引用配置生成表
import java.io.File;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class ClassToDB {
public static void main(String[] args){
Configuration config = null;
Session session = null;
Transaction tx = null;
try {
config = new Configuration().configure(new File(
"src/hibernate.cfg.xml"));
System.out.println("Creating tables...");
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true, true);
System.out.println("Table created.");
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
try {
tx.rollback();
} catch (HibernateException e1) {
e1.printStackTrace();
}
} finally {
}
}
}
POJO类举例
package cn.com.swansoft.sms.dao.pojo;
// Generated 2011-11-4 8:59:15 by Hibernate Tools 3.2.1.GA
import java.util.Date;
/**
* Sms generated by hbm2java
*/
public class Sms implements java.io.Serializable {
private Long id;
private String mobile;
private String message;
private Boolean send;
private Date addTime;
private Date sendTime;
private Date orderedTime;
private String username;
public Sms() {
}
public Sms(String mobile, String message, Date addTime) {
this.mobile = mobile;
this.message = message;
this.addTime = addTime;
}
public Sms(String mobile, String message, Boolean send, Date addTime, Date sendTime, String username) {