初识Hibernate

Hibernate

Hibernate 简介

什么是Hibernate?

Hibernate : ORM框架/持久层框架 jdbc 的一个框架
object reference mapping
通过管理对象来改变数据库中的数据、操作数据库
mybatis

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

Hibernate 的工作原理
①. 通过 Configuration 读取并解析 hibernate.cfg.xml 配置文件
②. 由 hibernate.cfg.xml 中的<mapping resource>读取并解析映射文件
③. 通过 config.buildSessionFactory 创建 sessionFactory
④. 通过 sessionFactory.openSession 获取 session
⑤. 通过 session.beginTransaction 开启事务
⑥. 操作数据
⑦. 提交事务
⑧. 关闭 session 和 sessionFactory

1.通过Configuration config = new Configuration().configure();//读取并解析hibernate.cfg.xml配置文件
2.由hibernate.cfg.xml中的<mapping resource="com/xx/User.hbm.xml"/>读取并解析映射信息
3.通过SessionFactory sf = config.buildSessionFactory();//创建SessionFactory
4.Session session = sf.openSession();//打开Sesssion
5.Transaction tx = session.beginTransaction();//创建并启动事务Transation
6.persistent operate操作数据,持久化操作
7.tx.commit();//提交事务
8.关闭Session
9.关闭SesstionFactory

添加Hibernate支持(手动添加)

具体步骤:

  • 添加hibernate相关依赖

  • 在resource目录下添加hibernate.cfg.xml(核心配置文件)
    添加DTD支持
    添加Hibernate的配置
    数据库相关:(connection.username|connection.password|connection.url|connection.driver_class|dialect)
    调试相关:
    (show_sql|format_sql)

  • 在开发阶段再创建实体类和实体映射文件(*.hbm.xml)
    实体必须实现Serializable接口

添加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.dj</groupId>
  <artifactId>pre_hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>pre_hibernate Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <!-- 第一步:导入相关依赖 pom依赖 -->
  <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>pre_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>

web.xml

代码如下:

<!-- 第二步:修改web.xml由2.3至3.0 -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
</web-app>


添加相应的配置文件

hibernate.cfg.xml(核心配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入dtd约束  configuration -->
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- 第三步:完成hibernate.cfg.xml的配置 -->

<!-- hibernate-configuration里面是hibernate所有相关的配置 -->
<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/dj?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/dj/one/entity/User.hbm.xml" />
		
	</session-factory>

</hibernate-configuration>

user.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入dtd约束  mapping -->
<!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标签:(id标签:配置的是表中的主键)
			name:对应的是实体类属性名
			type:实体类的数据类型
			column:数据库表对应的列段
			
		property:配置除去主键以外列段对应的类属性映射关系
			name:对应的是实体类属性名
			type:实体类的数据类型
			column:数据库表对应的列段
			
		insert="false" update="false"  含义:该列段(属性)只可查询,不可更新
	  -->
	
	<class name="com.dj.one.entity.User" table="user">
	
		<id name="id" type="java.lang.Integer" column="id">
			<generator class="increment" />
		</id>
		<property name="userName" type="java.lang.String" column="userName"></property>
		<property name="userPwd" type="java.lang.String" column="userPwd"></property>
		<property name="sex" type="java.lang.String" column="sex"></property>
		<property name="realName" type="java.lang.String" column="realName"></property>
		<property name="birthday" type="java.sql.Date" column="birthday"></property>
		<property insert="false" update="false" name="createDateTime"
			type="java.sql.Timestamp" column="createDateTime">
		</property>
		<property name="remark" type="java.lang.String" column="remark"></property>
		
	</class>
</hibernate-mapping>

实体类 User

相关属性代码:

	private Integer id;
	private String userName;
	private String userPwd;
	private String sex;
	private Date birthday;
	private String realName;
	private Timestamp createDateTime;
	private String remark;

实例 demo

重要代码:

查询:

package com.dj.one.demo;

import java.util.List;

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

/**
 * hibernate 查询演示
 * @author 86182
 *
 */
public class QueryDemo {
	public static void main(String[] args) {
		
		//得到对象
		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.clear();
	}
}

增加:
		session.save(new User(null, "蓝忘机", "111", "男", new Date(System.currentTimeMillis()), "蓝湛", new Timestamp(System.currentTimeMillis()), "二哥哥"));

删除:
		session.delete(new User(6));//根据 id 删除

修改:
		User user = session.get(User.class, 6);//从hibernate中取出的数据
		user.setRealName("含光君");//修改
		System.out.println(user);//可以修改成功
		
		//注意以下:
		//该 User 只存在于内存中 没有交给hibernate进行管理
		User u = new User(null, "蓝忘机", "111", "男", new Date(System.currentTimeMillis()), "蓝湛", new Timestamp(System.currentTimeMillis()), "二哥哥");
		u.setRealName("蓝二");//不能修改成功
		
	

Hibernate 管理对象的状态:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值