hibernate入门

hibernate入门

一.什么是hibernate?
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。Hibernate的核心接口一共有6个,分别为:Session、SessionFactory、Transaction、Query、Criteria和Configuration。

优势:跨数据库的无缝移植

注1:Object Relational Mapping
1、加载驱动
2、建立连接
3、获取预定义处理对象 preparestatment
4、执行sql
5、处理结果集
6、关闭

二. 如何在项目中添加hibernate支持(手动添加)
2.1 添加hibernate相关依赖
pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.javaxl</groupId>
   <artifactId>T224_hibernate</artifactId>
   <packaging>war</packaging>
   <version>0.0.1-SNAPSHOT</version>
   <name>T224_hibernate Maven Webapp</name>
   <url>http://maven.apache.org</url>

   <properties>
   	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   	<maven.compiler.source>1.8</maven.compiler.source>
   	<maven.compiler.target>1.8</maven.compiler.target>
   	<junit.version>4.12</junit.version>
   	<servlet.version>4.0.0</servlet.version>
   	<hibernate.version>5.3.0.Final</hibernate.version>
   	<mysql.driver.version>5.1.46</mysql.driver.version>
   </properties>

   <dependencies>  
   	<dependency>
   		<groupId>junit</groupId>
   		<artifactId>junit</artifactId>
   		<version>${junit.version}</version>
   		<scope>test</scope>
   	</dependency>

   	<dependency>
   		<groupId>javax.servlet</groupId>
   		<artifactId>javax.servlet-api</artifactId>
   		<version>${servlet.version}</version>
   		<scope>provided</scope>
   	</dependency>

   	<dependency>
   		<groupId>org.hibernate</groupId>
   		<artifactId>hibernate-core</artifactId>
   		<version>${hibernate.version}</version>
   	</dependency>

   	<dependency>
   		<groupId>mysql</groupId>
   		<artifactId>mysql-connector-java</artifactId>
   		<version>${mysql.driver.version}</version>
   	</dependency> 
   </dependencies>
   <build>
   	<finalName>T237_hibernate</finalName>
   	<plugins>
   		<plugin>
   			<groupId>org.apache.maven.plugins</groupId>
   			<artifactId>maven-compiler-plugin</artifactId>
   			<version>3.7.0</version>
   			<configuration>
   				<source>${maven.compiler.source}</source>
   				<target>${maven.compiler.target}</target>
   				<encoding>${project.build.sourceEncoding}</encoding>
   			</configuration>
   		</plugin>
   	</plugins>
   </build>
</project>

2.2 在resource目录下添加hibernate.cfg.xml(核心配置文件)
在这前还需要创建一个class类:
user.java:

package com.cbw.one.entity;

import java.sql.Date;
import java.sql.Timestamp;

import com.mysql.fabric.xmlrpc.base.Data;

public class User {
private Integer id;
private String userName;
private String userPwd;
private String realName;
private String sex;
private Date birthday;
private Timestamp createDatetime;
private String remark;
public Integer getId() {
	return id;
}
public void setId(Integer id) {
	this.id = id;
}
public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getUserPwd() {
	return userPwd;
}
public void setUserPwd(String userPwd) {
	this.userPwd = userPwd;
}
public String getRealName() {
	return realName;
}
public void setRealName(String realName) {
	this.realName = realName;
}
public String getSex() {
	return sex;
}
public void setSex(String sex) {
	this.sex = sex;
}
public Date getBirthday() {
	return birthday;
}
public void setBirthday(Date birthday) {
	this.birthday = birthday;
}
public Timestamp getCreateDatetime() {
	return createDatetime;
}
public void setCreateDatetime(Timestamp createDatetime) {
	this.createDatetime = createDatetime;
}
public String getRemark() {
	return remark;
}
public void setRemark(String remark) {
	this.remark = remark;
}
public User(Integer id, String userName, String userPwd, String realName, String sex, Date birthday,
		Timestamp createDatetime, String remark) {
	super();
	this.id = id;
	this.userName = userName;
	this.userPwd = userPwd;
	this.realName = realName;
	this.sex = sex;
	this.birthday = birthday;
	this.createDatetime = createDatetime;
	this.remark = remark;
}
public User() {
	super();
}

public User(String userName, String userPwd, String realName, String sex, Date birthday, Timestamp createDatetime,
		String remark) {
	super();
	this.userName = userName;
	this.userPwd = userPwd;
	this.realName = realName;
	this.sex = sex;
	this.birthday = birthday;
	this.createDatetime = createDatetime;
	this.remark = remark;
}
@Override
public String toString() {
	return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", realName=" + realName + ", sex="
			+ sex + ", birthday=" + birthday + ", createDatetime=" + createDatetime + ", remark=" + remark + "]";
}




}

user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <!-- class标签下的属性 
    name :指的是数据库中的表新映射的类的全路径名
    table:要映射的数据库表
    id标签
    name;数据库表的列段映射到实体类中的属性名
    type:属性名的类型
    column:数据库中的列段
    property标签:
    name:数据车表的列段映射到实体类中的属性名
    type:属性名的类型
    column: 数据库中的列段
    -->
	<class name="com.cbw.one.entity.User" table="t_hibernate_user">
		<id name="id" type="java.lang.Integer" column="id">
			<generator class="increment" />
		</id>
		<property name="userName" type="java.lang.String" column="user_name">
		</property>
		<property name="userPwd" type="java.lang.String" column="user_pwd">
		</property>
		<property name="realName" type="java.lang.String" column="real_name">
		</property>
		<property name="sex" type="java.lang.String" column="sex">
		</property>
		<property name="birthday" type="java.sql.Date" column="birthday">
		</property>
		<property insert="false" update="false" name="createDatetime"
			type="java.sql.Timestamp" column="create_datetime">
		</property>
		<property name="remark" type="java.lang.String" column="remark">
		</property>
	</class>

</hibernate-mapping>

hibernate.cfg.xml:

<?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>
		<!-- 1. 数据库相关 -->
		<property name="connection.username">root</property>
		<property name="connection.password">123</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/hib?useUnicode=true&amp;characterEncoding=UTF-8
		</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- 配置本地事务(No CurrentSessionContext configured!-->
		<property name="hibernate.current_session_context_class">thread</property>

		<!-- 2. 调试相关 -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>

		<!-- 3. 添加实体映射文件 -->
		<mapping resource="com/cbw/one/entity/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>

== 2.1 添加hibernate相关依赖
2.2 在resource目录下添加hibernate.cfg.xml(核心配置文件)
2.2.1 添加DTD支持
2.2.2 添加Hibernate的配置==
2.3 在开发阶段再创建实体类和实体映射文件(*.hbm.xml)
实体必须实现Serializable接口

三. hibernate核心API讲解
3.1 Configuration
读取hibernate.cfg.xml

3.2 SessionFactory(1)

3.3 Session(N)
注1:
注2:
3.3.1 save
3.3.2 get
load
3.3.3 delete(先查再删除,保证程序的健壮性)
User u = (User) session.get(User.class,99);
if(null!=u){
session.delete(u);//比如id=99不存在,直接删除就会报错
}
3.3.4 update
先查再改

      局部修改

3.3.4 createQuery        

3.4 Transaction(自动事务和手动事务讲解)
commit/rollback

3.5 Query(hql一章讲)
查全部/批量修改或删除
list
setXxx(String name,Xxx value);
setParameter(String name, Object value)
setParameterList(String name, Collection values)
setParameterList(String name, Object[] values)
setFirstResult/setMaxResults

四. 如何使用hibernate完成CRUD操作
4.1 CRUD操作步骤
4.1.1 读取配置
4.1.2 创建SessionFactory
4.1.3 打开Session
4.1.4 开启事务
4.1.5 CURD
4.1.6 提交事务/回滚事务
4.1.7 关闭Session
4.2 注意事项
4.2.1 hibernate默认使用的是手动事务,因此必须显示的开启和提交事务
4.2.2 删除操作时,必须先查再删

五.案列
首先我们查询(listDemo.java)

package com.cbw.one.test;

import java.util.List;

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

/**
* 演示hibernate查询
* @author 125x
*
*/
public class QueryDemo {
public static void main(String[] args) {
 /**
  * 1.对hibernate.cfg.xml这个核心配置文件进行建模
  * 2.建模后的对象去获得sessionfactory对象,sessionfactory数据库的相关信息
  * 3.通过sessionfactory对象去获取sess ion会话
  * 4、session开启事务(查询中是不需要)
  * 5、操作数据库
  * 6、提交事务(查询中是不需要)
  * 7、释放资源
  */
 Configuration configure =new Configuration().configure("/hibernate.cfg.xml");
 SessionFactory sessionFactory=configure.buildSessionFactory();
 Session session=sessionFactory.openSession();
 List list=session.createQuery("from User").list();
 for (Object obj : list) {
 	System.out.println(obj);
 }
 session.close();
}
}

结果:
在这里插入图片描述
增加:
addDemo:

package com.cbw.one.test;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;


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

import com.cbw.one.entity.User;

/**
 * 演示hibernate查询
 * @author 125x
 *
 */
public class addDeno {
public static void main(String[] args) {

	Configuration configure =new Configuration().configure("/hibernate.cfg.xml");
	SessionFactory sessionFactory=configure.buildSessionFactory();
	Session session=sessionFactory.openSession();
	//开实务
	Transaction transaction= session.beginTransaction();
	
	//控制数据库对象
	User user=new User("ls", "12345", "李四", "男", new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "吃饭睡觉打豆豆");
	session.save(user);
	//提交事务
	transaction.commit();
	session.close();
}
}

在这里插入图片描述
修改:
editDemo:

package com.cbw.one.test;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;


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

import com.cbw.one.entity.User;

/**
 * 演示hibernate查询
 * @author 125x
 *
 */
public class EditDeno {
public static void main(String[] args) {

	Configuration configure =new Configuration().configure("/hibernate.cfg.xml");
	SessionFactory sessionFactory=configure.buildSessionFactory();
	Session session=sessionFactory.openSession();
	//开实务
	Transaction transaction= session.beginTransaction();
	
/*	//方法一
	//控制数据库对象
	User user=new User("cbw", "12345", "楚霸王", "男", new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "撩一个妹子");
   //设置id
	user.setId(15);
	//赋予值
	session.update(user);*/
	
	//方法二
	User user=session.get(User.class, 15);
	user.setRealName("吴亦凡");
	System.out.println(user);
	
	//提交事务
	transaction.commit();
	session.close();
}
}

在这里插入图片描述
删除:
delDemo:

package com.cbw.one.test;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;


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

import com.cbw.one.entity.User;

/**
* 演示hibernate查询
* @author 125x
*
*/
public class delDemo {
public static void main(String[] args) {

  Configuration configure =new Configuration().configure("/hibernate.cfg.xml");
  SessionFactory sessionFactory=configure.buildSessionFactory();
  Session session=sessionFactory.openSession();
  //开实务
  Transaction transaction= session.beginTransaction();
  
  User user=new User();
  user.setId(15);
  session.delete(user);
  //提交事务
  transaction.commit();
  session.close();
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190829111403172.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ib3dlbmxlYXZl,size_16,color_FFFFFF,t_70)
  1. 工具类SessionFactoryUtil

  2. OID属性
    与数据库主键列映射的属性

SessionFactory对象的创建代价很昂贵,它是线程安全的对象,它为所有的应用程序线程所共享。它只创建一次,通常是在应用程序启动的时候,由一个Configuraion的实例来创建

Session对象的创建代价比较小,是非线程安全的,对于单个请求,单个会话、单个的 工作单元而言,它只被使用一次,然后就丢弃。只有在需要的时候,一个Session对象 才会获取一个JDBC的Connection(或一个Datasource) 对象,因此假若不使用的时候它不消费任何资源。

Hibernate3.3.2版本中getSession().connection()已被弃用,hibernate4中官方推荐使用Session doWork()方法进行jdbc操作
核心接口
在这里插入图片描述
Session接口

Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句。)。但需要注意的是Session对象是非线程安全的。同时,Hibernate的session不同于JSP应用中的HttpSession。这里当使用session这个术语时,其实指的是Hibernate中的session,而以后会将HttpSession对象称为用户session。

SessionFactory接口

SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。

Configuration类

Configuration类负责配置并启动Hibernate,创建SessionFactory对象。在Hibernate的启动的过程中,Configuration类的实例首先定位映射文档位置、读取配置,然后创建SessionFactory对象。

Transaction接口

Transaction接口负责事务相关的操作。它是可选的,开发人员也可以设计编写自己的底层事务处理代码

Query和Criteria接口

Query和Criteria接口负责执行各种数据库查询。它可以使用HQL语句或SQL语句两种表达方式。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值