初识Hibernate

Hibernate简介

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的JaveEE架构中取代CMP,完成数据持久化的重任。

在项目中添加hibernate支持

1、添加hibernate相关依赖

<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.lst</groupId>
	<artifactId>hibernate</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>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>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、在resource目录下添加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/db_0706?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/lst/one/entity/User.hbm.xml" />
		
		
	</session-factory>
</hibernate-configuration>

3、在开发阶段再创建实体类和实体映射文件(*.hbm.xml)
① 创建实体类 User

package com.lst.one.entity;

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

public class 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;
	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 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 String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	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;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", sex=" + sex + ", birthday="
				+ birthday + ", realName=" + realName + ", createDatetime=" + createDatetime + ", remark=" + remark
				+ "]";
	}
	public User(Integer id, String userName, String userPwd, String sex, Date birthday, String realName,
			Timestamp createDatetime, String remark) {
		super();
		this.id = id;
		this.userName = userName;
		this.userPwd = userPwd;
		this.sex = sex;
		this.birthday = birthday;
		this.realName = realName;
		this.createDatetime = createDatetime;
		this.remark = remark;
	}
	public User() {
		super();
	}
}

② 实体映射文件 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:指的是实体类数据类型
			colnum:数据库表对应的列段
			
		property:配置除去主键以外列段的类属性映射关系
			name:对应的是实体类属性名
			type:指的是实体类数据类型
			column:数据库表对应的列段
			insert="false" update="false"
			上面表示的含义是:该列段或者说该属性只做查询用,不做更新
		
	 -->
	
	<class name="com.lst.one.entity.User" table="tb_stu">
		<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完成增删查改

① 查询

/**
 * hibernate查询演示
 * @author Administrator
 *
 */
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.close();
	}
}

效果展示:
在这里插入图片描述
② 增加

/**
 * hibernate新增演示
 * @author Administrator
 *
 */
public class InsertDemo {
	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();
		session.save(new User(null, "cc", "123", "女", new Date(System.currentTimeMillis()), "sdf",  new Timestamp(System.currentTimeMillis()), "afdzsg"));
		
		transaction.commit();
		session.close();
	}
}

效果展示:
在这里插入图片描述
③ 修改

/**
 * hibernate修改演示
 * @author Administrator
 *
 */
public class UpdateDemo {
	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 = session.get(User.class, 3);
		user.setRealName("不老");
		System.out.println(user);
		
		transaction.commit();
		session.close();
	}
}

效果展示:
在这里插入图片描述
④ 删除

package com.lst.one.demo;

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.lst.one.entity.User;

/**
 * hibernate删除演示
 * @author Administrator
 *
 */
public class DeleteDemo {
	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(3);
		session.delete(user);
		
		transaction.commit();
		session.close();
	}
}

效果展示:
在这里插入图片描述

hibernate管理对象的三种状态
在这里插入图片描述

小结:

hibernate.cfg.xml(1)/*.hbm.xml(N)
实体映射文件一定要加到核心配置文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值