hibernate生成数据库表

hibernate生成数据库表

注:使用前需把数据库建好,运行完成后,原有数据会被清空

hibernate.cfg.xml

<?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">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="hibernate.connection.url">jdbc:sqlserver://192.168.56.101:1433;databasename=TestDB</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password">admin</property>
		<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
		<property name="connection.autoReconnect">true</property>
		<property name="connection.autoReconnectForPools">true</property>
		<property name="connection.is-connection-validation-required">true</property>
		<property name="hibernate.c3p0.min_size">2</property>
		<property name="hibernate.c3p0.timeout">5000</property>
		<property name="hibernate.c3p0.max_statements">100</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.validate">false</property>

		<mapping resource="com/lvy/server/model/Test.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;

/**
 * 通过hibernate配置文件生成数据库表
 * 
 * @author Albert Smith
 *
 */
public class InitDB {
	static Session session;

	public static void main(String[] args) {
		Configuration config = null;
		Transaction tx = null;
		try {
			config = new Configuration().configure(new File("config/hibernate.cfg.xml"));   //读取hibernate配置文件
			System.out.println("开始创表");
			SchemaExport schemaExport = new SchemaExport(config);
			schemaExport.create(true, true);
			System.out.println("创建结束");
			SessionFactory sessionFactory = config.buildSessionFactory();
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			try {
				tx.rollback();
			} catch (HibernateException e1) {
				e1.printStackTrace();
			}
		} finally {

		}
	}
}

每次修改hibernate配置文件后,运行一下,就可以自动更新表结构。

转载于:https://my.oschina.net/albert2011/blog/691219

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
private static void printTableMetaInfo(Session session) { Connection connection = session.connection(); try { DatabaseMetaData metaData = connection.getMetaData(); ResultSet result = metaData.getColumns(null, null, NameOfTable, null); String strInJava = ""; String typeInJava; while (result.next()) { String columnName = result.getString(4); if ("stampTime".equalsIgnoreCase(columnName)) { continue; } int columnType = result.getInt(5); String nameFirstLetterLower = columnName.substring(0, 1).toLowerCase() + columnName.substring(1); switch (columnType) { case Types.VARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.NVARCHAR: case Types.CHAR: typeInJava = "String"; break; case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: typeInJava = useInteger ? "Integer" : "int"; break; case Types.TIMESTAMP: case Types.BINARY: typeInJava = "Calendar"; break; case Types.DECIMAL: typeInJava = "BigDecimal"; break; case Types.BIGINT: typeInJava = "BigInteger"; break; case Types.LONGVARBINARY: typeInJava = "byte[]"; break; case Types.DATE: typeInJava = "Calendar"; break; default: throw new Exception("Unknown type " + columnType + " and column is " + columnName); } strInJava += " private " + typeInJava + " " + nameFirstLetterLower + ";\n"; // strInHibernate += "\n"; } String str = "import javax.persistence.Entity;\n" + "import javax.persistence.Id;\n" + "import javax.persistence.Table;\n" + "import java.util.Calendar;\n\n"; str += "@Entity\n"; str += "@Table(name=\"$\")\n".replace("$", NameOfTable); str += "public class $ {\n".replace("$", NameOfTable.substring(2)); str += "\n @Id\n"; str += strInJava; str += "}"; System.out.println(str); StringSelection stringSelection = new StringSelection(str); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); } catch (Exception e) { e.printStackTrace(); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值