使用hibernate的schemaExport 工具类实现将实体类转换成数据库中的表。在工程设计中,应该先设计表结构而不是先生成实体类,但是这只是个方法,虽然不推荐使用,但是还是需要记下来。
第一步:
在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=“数据库名字”
- 】
本文章转自网络,仅供学习交流用

本文介绍如何通过Hibernate的schemaExport工具类将实体类转换为数据库表。包括创建生成表的Java类、会话工厂类、配置文件及POJO映射文件的修改。


被折叠的 条评论
为什么被折叠?



