hibernate入门

  • Post author:
  • Post category:其他




hibernate框架

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


1.什么是hibernate


hibernate是一种ORM框架/持久层框架,也是jdbc的一个框架(也就是操作数据库的一种框架)

因为不需要配置servlet,所以用起来非常简便


2.如何在项目中添加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.qukang</groupId>
  <artifactId>T226_hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>T226_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>T226_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(核心配置文件)

在这里插入图片描述

3.添加DTD支持和Hibernate的配置

DTD约束支持在hibernate自带的jar包中已存在

在这里插入图片描述

hibernate.cfg.xml核心配置文件中添加DTD约束和相关的数据库配置和尸体映射文件

<?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="connection.username">root</property>
		<property name="connection.password">123</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/t226?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/qukang/one/entity/User.hbm.xml" />
		</session-factory>
	</hibernate-configuration>

4.创建实体类,属性名和类型需要和数据库匹配

package com.qukang.one.entity;

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

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

5.创建实体类对象映射的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:属性对应的类型,columu:属性对应的表中的哪一个列段
     		
     	property标签:
     		name:是实体类中的属性(映射的是表中的非主键字段),type:属性对应的类型,columu:属性对应的表中的哪一个列段
       -->
	<class name="com.qukang.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>

6.实现控制台对数据库进行增删改查

查询

package com.qukang.one.test;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * hibernate中查询
 * @param args
 */
public class QueryDemo {
	public static void main(String[] args) {
//	对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步)
		Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = configure.buildSessionFactory();
//	通过工厂获取到session会画(操作数据库的)
		Session session = sessionFactory.openSession();
//	直接操作数据库
		List list = session.createQuery("from User").list();
		for (Object object : list) {
			System.out.println(object);
		}
//	关闭资源	
		session.close();
	}
}

增加

package com.qukang.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.qukang.one.entity.User;
/**
 * hibernate中增加
 * @param args
 */
public class AddDemo {
	public static void main(String[] args) {
//		对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步)
			Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
			SessionFactory sessionFactory = configure.buildSessionFactory();
//		通过工厂获取到session会画(操作数据库的)
			Session session = sessionFactory.openSession();
//		获取事务对象
			Transaction beginTransaction = session.beginTransaction();
//		直接操作数据库
			session.save(new User("qukang", "123","屈康","男",new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无"));
//		提交事务	
			beginTransaction.commit();
//		关闭资源	
			session.close();
}
}

修改

注意:修改数据需根据实列状态来进行操作,具体管理对象的状态如下图

临时状态 因没有和session挂钩,所以被无视

Session session = sessionFactory.openSession();
Transaction beginTransaction = session.beginTransaction();
User user=new User("qukang2", "1234","屈康2","男",new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无");
user.setRealName("屈康3");
beginTransaction.commit();
session.close();

持久状态 当session.get()方法被调用,操作的数据会直接修改数据库

Session session = sessionFactory.openSession();
Transaction beginTransaction = session.beginTransaction();
User user = session.get(User.class,15);
user.setRealName("屈康3");
beginTransaction.commit();
session.close();

游离状态就 是在session关闭之后进行操作的对象状态

Session session = sessionFactory.openSession();
Transaction beginTransaction = session.beginTransaction();
session.close();
User user = session.get(User.class,15);
user.setRealName("屈康3");
beginTransaction.commit();

在这里插入图片描述

package com.qukang.one.test;

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

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

import com.qukang.one.entity.User;
/**
 * hibernate中修改
 * @param args
 */
public class EditDemo {
	public static void main(String[] args) {
//		对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步)
			Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
			SessionFactory sessionFactory = configure.buildSessionFactory();
//		通过工厂获取到session会画(操作数据库的)
			Session session = sessionFactory.openSession();
//		获取事务对象
			Transaction beginTransaction = session.beginTransaction();
//		直接操作数据库
			
//			第一种
//			User user=new User("qukang2", "1234","屈康2","男",new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无");
//			user.setId(15);
//			session.update(user);
//			第二种 
			User user = session.get(User.class,15);
			user.setRealName("屈康3");
//		提交事务	
			beginTransaction.commit();
//		关闭资源	
			session.close();
}
}

查询

package com.qukang.one.test;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * hibernate中查询
 * @param args
 */
public class QueryDemo {
	public static void main(String[] args) {
//	对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步)
		Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = configure.buildSessionFactory();
//	通过工厂获取到session会画(操作数据库的)
		Session session = sessionFactory.openSession();
//	直接操作数据库
		List list = session.createQuery("from User").list();
		for (Object object : list) {
			System.out.println(object);
		}
//	关闭资源	
		session.close();
	}
}

SQL语句的形成过程

例如以上代码:

1、建模hibernate.cfg.xml对象,从中拿到了com/qukang/one/entity/user.hbm.xml

2、建模user.hbm.xml对象,就拿到了实体类com.qukang.one.entity.User和对应的数据库表格t_hibernate_user

3、User user=Claas.forName(“com.qukang.one.entity.User”).newInstance();

Field userUname=user.getClass(“uname”); 拿到一个一个的属性

sql语句就形成了,就可以得到源数据

userUname.set(user,列名对应的数据) 就拿到了数据库中的数据…最后user中的所有属性值都有了

4、循环上一步,最后所有user实例都放入list集合中



版权声明:本文为weixin_45176922原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。