读书人

hibernate 种生成表 的实现源码

发布时间: 2012-09-06 10:37:01 作者: rapoo

hibernate 类生成表 的实现源码
第一步:
在test包中创建一个生成表的java类:

package com.test;import org.hibernate.cfg.Configuration;import org.hibernate.tool.hbm2ddl.SchemaExport;public class 生成表 {/** * @param args */public static void main(String[] args) {Configuration cfg = new Configuration().configure();SchemaExport ex   = new SchemaExport(cfg);ex.create(true, true);}}



第二步:
写一个创建session的类:
package com.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateSessionFactory {private static Configuration cfg = new Configuration().configure();private static SessionFactory factory = cfg.buildSessionFactory();private static ThreadLocal<Session> local  = new ThreadLocal<Session>();public static Session getSession(){Session session = local.get(); //取if (session==null || session.isOpen()==false){session = factory.openSession();local.set(session); //存}return session;}    }


第三步:
修改hibernate的配置文件相关属性、驱动。
<?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><property name="myeclipse.connection.profile">【这里是什么数据库就写什么】mysql</property><property name="connection.url">【数据库连接是什么数据库写什么数据库test】jdbc:mysql://localhost:3306/test</property><property name="dialect">【是mysql就写mysql orc就orc】org.hibernate.dialect.MySQLDialect</property><property name="connection.username">root</property><property name="connection.password">admin</property><property name="connection.driver_class">【驱动要改 】com.mysql.jdbc.Driver</property><property name="show_sql">true</property><property name="format_sql">true</property><mapping resource="com/pojos/TSaleformDetail3.hbm.xml" /><mapping resource="com/pojos/TSaleform3.hbm.xml" /></session-factory></hibernate-configuration>




第四步 改pojo映射文件:

<hibernate-mapping>    <class name="com.pojos.TSaleform3" table="T_SALEFORM3" schema="test">【这地方的schema=“数据库名字”】



读书人网 >软件架构设计

热点推荐