在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();
}
}
运行结果截图: