使用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=“數據庫名字”
- 】
本文章轉自網絡,僅供學習交流用