您的位置:首页 > 编程语言 > Java开发

Hibernate初学者---Hello World

2017-09-05 14:17 369 查看
hibernate-release-5.2.10.Final版本学习笔记

1,hibernate.org 下载最新版,解压不用安装。

2,新建JAVA项目,项目中引入lib文件下所有JAR包,一共才30M 省心了!

同时要下载MYSQL的JDBC驱动包引入到项目中



3,项目src 目录下创建hibernate.cfg.xml文件

cfg为configuration的缩写,表示这是一份hibernate的配置文件

<?xml version="1.0" encoding="utf-8"?>

<!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>
<!-- 数据库驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 指定数据库名-->
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<!-- 指定用户名 -->
<property name="connection.username">root</property>
<!-- 指定密码 -->
<property name="connection.password">shwythnn00</property>
<!-- 指定数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否自动创建数据表 -->
<!--<property name="hbm2ddl.auto">update</property>  -->
<!-- 显示SQL语句 -->
<property name="show_sql">true</property>
<!--输出前格式化SQL语句 -->
<property name="hibernate.format_sql">true</property>
<!-- 映射文件 -->
<mapping resource="com/fan/bai/Baifan.hbm.xml"/>
</session-factory>
</hibernate-configuration>


4,新建对象模型类,设置对象属性并分别生成get&set方法,

5, 新建MYSQL数据库及数据库表。表名与对象模型类名相同,表属性与对象模型属性一一对应。

create database hibernate;

use hibernate;

create table xxx(id int primary key,name varchar(20),age int);

6,在对象模型根目录下创建——类名.hbm.xml形式的文件。

这里的hbm是hibernate mapping的缩写,表示 这是一份hibernate的映射文件

<?xml version="1.0"?>
<!--
~ 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-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="包路径 "

<class name="类名" table="数据库表名">
<id name="类主属性"  column="表主键名"> </id>
<property name="类其它属性" />
<property name="类其它属性"/>
</class>

</hibernate-mapping>


7,创建测试类生成Main方法,

a, NEW对象模型

b, 调用set方法赋值

c, 创建Configuration对象

d, 调用Configuration的buildSessionFactory()方法返回一个SessionFactory对象

e,利用返回的SessionFactory对象NEW 一个新的SessionFactory对象

f, 调用SessionFactory的openSession()方法,返回一个新的Session

g, 利用返回的Session,NEW一个新的Session对象

h,调用Session对象的beginTransaction()方法,准备接收线程参数。

i, 调用Session的save方法传入NEW出来的对象模型。

j, 调用Session对象的getTransaction().commit()方法,提交接收到的参数。

k, 关闭Session

l, 关闭SessionFactory

8,启动测试,

9,进入数据库验证结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate java jar