一,Hibernate框架介绍  

  没有Hibernate之前,使用jdbc来连接数据库时,需要反射加载驱动,再获取连接

  在连接上获取sql承载块,传入sql语句执行,获取结果集,解析结果

  Hibernate框架,核心对象就是使用连接字串获取的session,自动完成对象关系映射,不需要手动来解析对象

二,程序实例

1.新建web项目,导入框架包

2.编写  User.java

package com.zhaolong.bean;

import java.sql.Date;

public class User {

    private Integer id;
private String name;
private String gender;
private String age;
private Date birthday;
private String phone;
private String address;
private String card;
private String email;
private String wechat;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
} public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWechat() {
return wechat;
}
public void setWechat(String wechat) {
this.wechat = wechat;
} public User(String name, String gender, String age, Date birthday,
String phone, String address, String card, String email,
String wechat) {
super();
this.name = name;
this.gender = gender;
this.age = age;
this.birthday = birthday;
this.phone = phone;
this.address = address;
this.card = card;
this.email = email;
this.wechat = wechat;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", gender=" + gender
+ ", age=" + age + ", birthday=" + birthday + ", phone="
+ phone + ", address=" + address + ", card=" + card
+ ", email=" + email + ", wechat=" + wechat + "]";
} }

3.编写实体类的映射文件  User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.zhaolong.bean.User" table="HUQB_USER">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="gender"/>
<property name="age"/>
<property name="birthday"/>
<property name="phone"/>
<property name="address"/>
<property name="card"/>
<property name="email"/>
<property name="wechat"/>
</class> <!-- 创建命名查询 --> <query name="findAllUsers">
<![CDATA[
from User
]]>
</query> <!-- 查询年龄大于30的所有人 -->
<query name="findUsersByAge">
<![CDATA[
from User u where u.age>:age
]]>
</query> <!-- 本地命名查询 -->
<sql-query name="findAllUsersLocal">
<!-- 通过return 标签指定返回结果的映射 -->
<return class="com.zhaolong.bean.User"/>
<![CDATA[
select * from huqb_user
]]>
</sql-query> </hibernate-mapping>

4.编写连接字串配置文件  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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<!--<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">java</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
-->
<!-- 配置方言 -->
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<!-- 配置连接地址 -->
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<!-- 配置用户名 -->
<property name="connection.username">mart</property>
<!-- 配置密码 -->
<property name="connection.password">java</property>
<!-- 配置驱动 -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="show_sql">true</property>
<!-- 对sql语句进行格式化 -->
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/zhaolong/bean/User.hbm.xml"/>
</session-factory> </hibernate-configuration>

5.根据cfg文件获取操作数据库的session,可以自己编写,也可以选择自动生成  HibernateSessionFactory

package com.zhaolong.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration; /**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
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() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
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;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }

6.编写数据测试类  AddTest

package com.zhaolong.test;

import java.sql.Date;

import org.hibernate.Session;
import org.hibernate.Transaction; import com.zhaolong.bean.User;
import com.zhaolong.util.HibernateSessionFactory; public class AddTest { public static void main(String[] args) { Session session = HibernateSessionFactory.getSession(); Transaction tx = session.beginTransaction(); User u1=new User("诸葛亮", "男", "35",
new Date(System.currentTimeMillis())
, "110", "蜀国", "1234567890", "zgl@huqb.com", "zhugeliang01");
User u2=new User("黄月英", "女", "33",
new Date(System.currentTimeMillis()+100000000)
, "119", "蜀国", "0987654321", "hyy@huqb.com", "huangyueying01"); User u3=new User("曹丕", "男", "45",
new Date(System.currentTimeMillis())
, "120", "魏国", "1234567890", "cp@huqb.com", "caopi");
User u4=new User("甄姬", "女", "33",
new Date(System.currentTimeMillis()+100000000)
, "114", "魏国", "0987654321", "zj@huqb.com", "zhenji01");
User u5=new User("荀彧", "男", "45",
new Date(System.currentTimeMillis())
, "120", "魏国", "1234567890", "cp@huqb.com", "caopi");
User u6=new User("曹操", "男", "33",
new Date(System.currentTimeMillis()+100000000)
, "114", "魏国", "0987654321", "zj@huqb.com", "zhenji01"); session.save(u1);
session.save(u2);
session.save(u3);
session.save(u4);
session.save(u5);
session.save(u6);
tx.commit(); session.close(); }
}

Hibernate框架用法的更多相关文章

  1. 1.Hibernate框架核心组件 (转自冯岩)

    Hibernate框架核心组件 在Hibernate框架简述中,演示了一个简单的Hibernate应用,但并没有深入说明其中程序,在这篇中将比较详细的介绍一下Hibernate的核心组件.首先最关键一 ...

  2. 粗浅看Struts2和Hibernate框架

    ----------------------------------------------------------------------------------------------[版权申明: ...

  3. Hibernate框架_搭建第一个Hibernate框架

    一.eclipse搭建 A.创建动态web项目 New-->Dynamic web project(web project) B.导入jar包 1.数据库驱动包 2.hibernate开发必须j ...

  4. Hibernate框架之Criteria查询 和注解(重点☆☆☆☆☆,难点☆☆☆)

    写好一篇博客,不是容易的事.原因是:你要给自己以后看的时候,还能看懂,最重要的是当别人看到你的博客文章的时候,也一样很清楚的明白你自己写的东西.其实这也是一种成就感!! 对于每一个知识点,要有必要的解 ...

  5. Hibernate 系列 01 - 框架技术 (介绍Hibernate框架的发展由来)

    引导目录: Hibernate 系列教程 目录 本篇导航: 为什么学习框架技术 框架的概念 主流框架的介绍 1.为什么学习框架技术 如何制作一份看上去具有专业水准的PPT文档呢?一个简单的方法就是使用 ...

  6. 2.0、Hibernate框架的简单搭建

    一.Hibernate:是一个开放源代码的对象关系映射框架,对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句 ...

  7. 【Hibernate框架】对象的三种持久化状态

    一.综述 hibernate中的对象有三种状态,分别是TransientObjects(瞬时对象).PersistentObjects(持久化对象)和DetachedObjects(托管对象也叫做离线 ...

  8. hibernate框架int和Integer类型区别

    hibernate 框架在定义实体时,int类型最好定义为Inttger类型,因为在注入时int是值类型不允许为空.

  9. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

随机推荐

  1. IOS 了解新技术(UIPresentationController,屏幕适配)

    1.了解有什么新技术1> 苹果API文档 - General - Guides - iOSx API Diffs2> 观看WWDC会议视频 2.如何使用新技术 1> 自己根据API文 ...

  2. 2763. [JLOI2011]飞行路线【分层图最短路】

    Description Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司.该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并 ...

  3. Django中的CBV和FBV

    Django中的CBV和FBV 一.  CBV CBV是采用面向对象的方法写视图文件. CBV的执行流程: 浏览器向服务器端发送请求,服务器端的urls.py根据请求匹配url,找到要执行的视图类,执 ...

  4. [19/04/29-星期一] GOF23_行为型模式(责任链模式、迭代器模式)

    一.行为模式 二.责任链模式(chainOfResponsibility) [一个请求类] /*** 请假类 * 封装请假的基本信息 */ package cn.sxt.chainOfResponsi ...

  5. 1、Spring Cloud - 微服务简介

    前言: 业界大牛马丁.福勒(Martin Fowler) 这样描述微服务: 论文网址:https://martinfowler.com/articles/microservices.html 就目前而 ...

  6. linq的左连接右连接内连接用法

    1.左连接: var LeftJoin = from e in ListOfEmployees join d in ListOfDepartment on e.DeptID equals d.ID i ...

  7. 测试用例组合--PICT

    测试用例组合 一原理 1.配对组合原理(两两组合原理),应用工具PICT自动输出组合 name=a,b value=1,2 key=m,n 如果自己组合那么有2*2*2=8条用例 a1m a2m a1 ...

  8. LWIP network interface 即 LWIP 的 硬件 数据 接口 移植 详解 STM32 以太网数据 到达 的第二站: void ethernetif_input( void * pvParameters )

    根据 上一篇 文章 , ETH  DMA 数据中断 会 发送 一个信号量 ,我使用 全局 搜索 这个信号量 s_xSemaphore 得到 一下 几个 值 根据 这个 分析  我们找到了   数据 的 ...

  9. Linux 嵌入式 开发环境 交叉编译安装

    1.安装 Ubuntu 系统 安装完毕,系统 提示 重启,这个时候 请拔掉U盘,进行重启 OK. 2.安装 NFS 服务 3.安装 openssh服务 4.开启openSSH服务 5.就可以使用 Wi ...

  10. C#中如何利用操作符重载和转换操作符 (转载)

    操作符重载 有的编程语言允许一个类型定义操作符应该如何操作类型的实例,比如string类型和int类型都重载了(==)和(+)等操作符,当编译器发现两个int类型的实例使用+操作符的时候,编译器会生成 ...