hibernate 类生成表 的实现源码

本文介绍如何通过Hibernate框架自动生成数据库表,包括创建生成表的Java类、会话工厂类,配置Hibernate设置以及修改POJO映射文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:
在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=“数据库名字”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值