hibernate入门

hibernate自动建学生表

最近学习了hibernate,现在来整理一下做的一个小demo,根据配置文件在数据库自动建立学生表。

准备工作:

        IDE工具:mysql+eclipse

        entity实体类+对应的配置文件:Student.java,Student.hbm.xml。实体类用于记录实体Student的属性和方法,实体类配置文件用于配置数据库表与实体的对应关系。

        utils工具包:HibernateSessionFactory.java,用于获取session。

  hibernate.cfg.xml总配置文件:配置属性property,指定连接数据库的driver,url,username,password,hbm2ddl.auto,show_sql。以及配置映射文件mapping。

        execute包:executeService.java,执行main方法。

        建立数据库test:数据库要手动建立,hibernate只会自动建表,不会自动建库。


具体代码如下:

Student.java:

package entity;
public class Student {

	private String student_id;
	private String sname;
	private int age;
	public String getStudent_id() {
		return student_id;
	}
	public void setStudent_id(String student_id) {
		this.student_id = student_id;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [student_id=" + student_id + ", sname=" + sname + ", age=" + age + "]";
	}
	

Student.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
        
 <hibernate-mapping>
 	<class name="entity.Student" table="student">
 		<id name="student_id" column="student_id">
 			<!-- 自动匹配MySQL或Oracle -->
			<!-- <generator class="native" />  -->
	         <!-- 程序指定 -->
			 <generator class="assigned" />  
 		</id>
 		
 		<property name="sname" column="sname" type="java.lang.String" ></property>
 		<property name="age" column="age" type="int" ></property>
 	</class>
 </hibernate-mapping>
HibernateSessionFactory.java
package utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {

    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}
        return session;
    }

	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}
	public static Configuration getConfiguration() {
		return configuration;
	}

}

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.url">
	    	jdbc:mysql://localhost:3306/test
	    </property>
       	<property name="hibernate.connection.driver_class">
       		com.mysql.jdbc.Driver
       	</property>
       	<!-- Hibernate格式化SQL语句 -->
		<property name="hibernate.format_sql">true</property>
		<!-- Hibernate的方言:作用,根据配置的方言生成相应的SQL语句-->
       	 <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
       	<property name="hibernate.connection.username">root</property>
       	<property name="hibernate.connection.password">root</property>  
		<!-- 是否启动表结构自动生成 -->
		<property name="hbm2ddl.auto">update</property>
		<!-- 是否在控制台显示SQL语句 -->
		<property name="show_sql">true</property>
            
        <!-- 2018-07-06 -->
         <mapping resource="entity/Student.hbm.xml" />
  
    </session-factory>
</hibernate-configuration>

executeService.java:

package execute;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class executeService {

	public static void main(String[] args) {
		Configuration conf = new Configuration().configure();// 读取并解析配置文件
		SchemaExport export = new SchemaExport(conf);// 创建SchemaExport
		// 执行生成表。参数1:是否显示sql语句,参数2:是否到数据库里执行
		export.create(true, true);
	}
}
执行main方法,会发现数据库自动建立了一个student表,至此成功入门hibernate,完成其配置文件的编写。后面会将运用hibernate操作数据库,实现增删改查操作。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值