hibernate自动建表

在hibernate自动建表操作中,hibernate不会创建数据库,数据库的创建要手动去完成。创建数据库后就可以通过实体类由hibernate自动去创建数据库表了。

配置文件hibernate.cfg.xml

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
	    <!-- 在控制台显示SQL语句 -->
		<property name="show_sql">true</property>
		<!-- 连接数据库的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		<!-- 连接数据库的驱动名 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 连接数据库的URL -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/abc</property>
		<!-- 连接数据库的用户名 -->
		<property name="hibernate.connection.username">root</property>
		 <!-- 连接数据库的密码 -->
		<property name="hibernate.connection.password">sunrui1314</property>
		<!--<property name="hibernate.hbm2ddl.auto">create</property>  -->
		
		<!-- 保证每个线程有一个属于自己的Session对象 -->
		<property name = "hibernate.current_session_context_class">thread</property>
		<mapping resource="com/Entity/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

之后创建实体类

接着做测试

package com.DAO;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.junit.Test;

import com.Entity.User;

public class UserDAO {
	
@Test //add
	public void saveUser(){
		SessionFactory sf = null;	
		Session session = null;
		Transaction ts = null;
		User user=new User();
		user.setAge(50);
		user.setUsername("噗噗噗");
		user.setPassword("12356");
		user.setGender("女");
		try{
  			sf = HibernateUtil.getSessionFactory();
			session = sf.getCurrentSession();
			ts = session.beginTransaction();
			session.save(user);
			ts.commit();
			
		}catch(HibernateException e){
			e.printStackTrace();
			ts.rollback();
		}
	}

运行结果截图:





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值