hibernate入门篇

概念:hibernate是一个轻量级的、企业级的、开源的ORM持久层框架

目标:在eclipse中实现一个用hibernate实现的第一个小案例

1、创建一个java或者web工程

2、项目下创建一个lib文件夹,导jar包用

3、导jar包,需要导入三部分:hibernate开发包中的required文件夹下几个包、log4j jar包、数据库驱动jar包

它们都可以在官网下载,拷贝导lib里后build path

4、创建好Java中的Javabean类User和数据库中的表user,注意类实现序列号接口

5、写好User.hbm.xml文件

    过程中需要添加dtd约束,如果记不住没关系,可以去hibernate-core-5.3.1.Final.jar/org.hibernate/hibernate-mapping-3.0.dtd这个文件中找到

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

然后在preferences中搜索xml c就会找到XML Catalog,选择User Specified Entries,点击add

在里面的location可选工作空间或本地,我选本地,然后找到那个dtd文件,在这个目录下:hibernate-release-5.3.1.Final/project/hibernate-core/src/main/resources/org/hibernate,key type选择URI, key就是上图中的网址:

http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd,配置好了以后再去xml文件里写配置就会有提示信息了。

6、再写hibernate.config.xml,这个默认就放在src下了,一般不要去改它,要改了以后在后面new Configration的时候就要指定路径了,没必要啊!

    也是先添加dtd约束,然后去xml catalog里配置一样,方法同上。

    配置session-factory的时候三部分(这部分配置不需要记,去这个文件中找:/hibernate-release-5.3.1.Final/project/etc/hibernate.properties  ,然后mapping resource指定路径时应该是相对路径,反正我开始用绝对路径时报错了):

                        <!-- 第一部分,数据库连接配置 -->
			<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
			<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
			<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testDB</property>
			<property name="hibernate.connection.username">username</property>
			<property name="hibernate.connection.password">password</property>
			<!-- 第二部分,hibernate可选配置 -->
			<property name="hibernate.show_sql">true</property>
			<property name="hibernate.format_sql">true</property>
			<property name="hibernate.hbm2ddl.auto">update</property>
	<!-- 第三部分,指定hbm.xml的位置 -->后面学习了注解方式以后,这里配置就变成这样<mapping class = "com.dimples.dao.User"/>
			<mapping resource="com/dimples/dao/User.hbm.xml"/>

7、最后写一个测试类运用junit进行测试即可

package com.dimples.service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.dimples.dao.User;


public class Test1 {
	@Test//这里使用了注解,直接在方法上加上@Test会提示你添加junit库,添加就是了,或者自己下载junit jar包再导入然后build path也行
	public void trySave() {//使用junit测试到好处是可以测试单独的方法
		User user = new User();
		user.setUsername("test");
		user.setPassword("123456");
		//解析config配置文件
		Configuration cfg = new Configuration();
		cfg.configure();
		//根据cfg创建SessionFactory
		SessionFactory sf =  cfg.buildSessionFactory();
		//根据SessionFactory创建session
		Session session = sf.openSession();
		//开启事务
		Transaction ts = session.beginTransaction();
		//执行操作
		session.save(user);
		//提交事务
		ts.commit();
		//关闭资源
		session.close();
		sf.close();
	}
}


猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/80778505