hibernate学习-基本技术-第2天

代码地址:https://github.com/MisterChegy/hibernate.git

IDE:eclipse(Java EE)
环境:JDK1.8
Hibernate:5.01
数据库:MySQL5.7

一、Hibernate 工作原理

在这里插入图片描述

二、Eclipse实现hibernate反向工程

转载:Eclipse实现hibernate反向工程:从数据库逆向生成实体类和hbm文件
转载:eclipse 逆向工程生成hibernate实体类(注解或配置文件)

注解方式:
在这里插入图片描述
逆向工程作用:
1,通过数据库表逆向生成实体
2,注解和表这间的关系也会生成

三、第一个 Hibernate 程序

1、定义持久化对象(PO)

@Entity
@Table(name = "student", catalog = "test")
public class Student implements java.io.Serializable {

	private int sid;
	private String sname;

	public Student() {
	}

	public Student(int sid) {
		this.sid = sid;
	}

	public Student(int sid, String sname) {
		this.sid = sid;
		this.sname = sname;
	}

	@Id
	@Column(name = "sid", unique = true, nullable = false)
	public int getSid() {
		return this.sid;
	}

	public void setSid(int sid) {
		this.sid = sid;
	}

	@Column(name = "sname", length = 45)
	public String getSname() {
		return this.sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

}

2、配置映射文件(注解方式和xml等同,这里在实体中用注解实现,不用配置)
配置映射文件,即配置两个关系:实体类与数据库中表的映射关系,属性与表中字段
的映射关系。

3、配置主配置文件(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>
        <property name="myeclipse.connection.profile">test</property>
	<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
	<property name="connection.password">xxxx</property>
	<property name="connection.username">root</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF8
	</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="format_sql">true</property>
	<property name="show_sql">true</property>
	<property name="hbm2ddl.auto">update</property>
	<property name="current_session_context_class">thread</property>
	
	<mapping class="model.Student" />
	
    </session-factory>
</hibernate-configuration>

Unicode=true&characterEncoding=UTF8是解决
4、创建数据库

5、定义测试类
在这里插入图片描述
6、修改测试类
通过 openSession()方式获取到的 Session 无法保证在同一个线程中使用的为同一个
Session,因为每执行一次 openSession(),都会创建一个新的 Session 对象。改变 Session 的
获取方式为 getCurrentSession(),会保证每个线程中的 Session 对象为同一个 Session。
注意,该方式获取到的 Session,必须在事务内执行,无论是增、删、改,还是查询。
且其无需再手工关闭 Session 对象,而是在事务提交或回滚后,自动将 Session 关闭了。
在这里插入图片描述
7、修改主配置文件
通过 getCurrentSession()获取 Session,需要在主配置文件中对 Session 所处的上下文环
境,即事务环境进行注册。这里指定其上下文件事务环境为线程,即一个线程一个事务。(上面配置完全)
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值