Hibernate之单表操作

版本:hibernate-release-5.0.7.Final

基本开始,所需jar包:





1.创建实体类

User.java

package zh.hibernate.entity;

/**
 * 实体类:即持久化类
 * @author ZH
 */
public class User {

	// 整型变量作为主键,主键生成策略设置为native
	// 字符串型变量作为主键,主键生成策略设置为uuid
	private Integer uid;
	private String username;
	private String password;
	private String address;

	public User() {

	}

	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [uid=" + uid + ", username=" + username + ", password="
				+ password + ", address=" + address + "]";
	}

}


2.创建映射文件

通常在实体类所在包下,创建映射文件User.hbm.xml

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="zh.hibernate.entity.User" table="t_user">
		<!-- 实体类的uid属性映射为表的主键 -->
		<id name="uid" column="uid">
			<!-- 主键生成策略:自动增长 -->
			<generator class="native"></generator>
		</id>
		<!-- 实体类的其它属性映射为表的字段 -->
		<property name="username" column="username"></property>
		<property name="password" column="password"></property>
		<property name="address" column="address"></property>
	</class>

</hibernate-mapping>

3.创建核心配置文件

在src下创建核心配置文件:hibernate.cfg.xml。

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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 驱动类 -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb1</property> <!-- 路径 -->
		<property name="hibernate.connection.username">root</property> <!-- 用户名 -->
		<property name="hibernate.connection.password">1980217948</property> <!-- 密码 -->
		
		<!-- 可选:配置Hibernate信息 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 方言 -->
		<property name="hibernate.show_sql">true</property> <!-- 显示SQL语句 -->
		<property name="hibernate.format_sql">true</property> <!-- 格式化SQL语句 -->
		<property name="hibernate.hbm2ddl.auto">update</property> <!-- 无表创建,有表更新 -->
		
		<!-- 必须:引入映射文件 -->
		<mapping resource="zh/hibernate/entity/User.hbm.xml"/>
	
	</session-factory>

</hibernate-configuration>

附:



4.创建HibernateUtil工具类

HibernateUtils.java

package zh.hibernate.utils;

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

public class HibernateUtils {

	private static Configuration configuration;
	private static SessionFactory sessionFactory;

	// 静态代码块,加载src下的hibernate.cfg.xml
	static {
		configuration = new Configuration();
		configuration.configure();
		// 创建SessionFactory时,会根据实体类和表的映射关系,在数据库中创建表
		sessionFactory = configuration.buildSessionFactory();
	}

	// 获取sessionFactory
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	
}

5.添加操作

SaveTest.java

package zh.hibernate.test;

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

import zh.hibernate.entity.User;
import zh.hibernate.utils.HibernateUtils;

/**
 * 添加操作:session.save(实体类对象)
 * @author ZH
 */
public class SaveTest {

	public static void main(String[] args) {

		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();// 开启事务
			
			// User.hbm.xml中已经设置uid为主键,且自动增长,因此,在添加对象时,无需为对象设置uid
			User user1 = new User();
			user1.setUsername("郭靖");
			user1.setPassword("1000");
			user1.setAddress("桃花岛");

			User user2 = new User();
			user2.setUsername("黄蓉");
			user2.setPassword("2000");
			user2.setAddress("桃花岛");

			session.save(user1);// 添加对象
			session.save(user2);// 添加对象

			transaction.commit();// 提交事务
		} catch (Exception e) {
			transaction.rollback();// 回滚事务
		} finally {
			session.close();// 关闭session
			sessionFactory.close();// 实际开发中,不需要关闭
		}

	}

}

结果:


控制台输出:


6. 查询操作

【立即查询】

GetTest.java

package zh.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import zh.hibernate.entity.User;
import zh.hibernate.utils.HibernateUtils;

/**
 * 立即查询:session.get(对象类型,id)
 * @author ZH
 */
public class GetTest {

	public static void main(String[] args) {
		
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();// 开启事务
			 
			User user1 = session.get(User.class, 1);// 立即发送查询语句
			System.out.println(user1);// User [uid=1, username=郭靖, password=1000, address=桃花岛]

			transaction.commit();// 提交事务
		} catch (Exception e) {
			transaction.rollback();// 回滚事务
		} finally {
			session.close();// 关闭session
			sessionFactory.close();// 实际开发中,不需要关闭
		}
		
	}
	
}

【延迟查询】

LoadTest.java

package zh.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import zh.hibernate.entity.User;
import zh.hibernate.utils.HibernateUtils;

/**
 * 延迟查询:session.load(对象类型,id)
 * @author ZH
 */
public class LoadTest {

	public static void main(String[] args) {
		
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();// 开启事务
			
			User user = session.load(User.class, 1);// 不会发送查询语句,user中只有id属性有值,其它属性没有值
			System.out.println(user);// 当获取对象中除id属性之外的属性时,才发送查询语句
			
			transaction.commit();// 提交事务
		} catch (Exception e) {
			transaction.rollback();// 回滚事务
		} finally {
			session.close();// 关闭session
			sessionFactory.close();// 实际开发中,不需要关闭
		}

	}
	
}


7.修改操作

UpdateTest.java

package zh.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import zh.hibernate.entity.User;
import zh.hibernate.utils.HibernateUtils;

/**
 * 修改操作:
 * @author ZH
 */
public class UpdateTest {

	public static void main(String[] args) {
		
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();// 开启事务
			// 先查询,再修改
			User user = session.load(User.class, 1);// 不发生查询语句
			user.setAddress("襄阳");// 发送查询语句
			
			//session.update(user);// 词句可以省略,因为存在一级缓存和快照区
			
			transaction.commit();// 提交事务
		} catch (Exception e) {
			transaction.rollback();// 回滚事务
		} finally {
			session.close();// 关闭session
			sessionFactory.close();// 实际开发中,不需要关闭
		}

	}
	
}

修改前,


修改后,


8.删除操作

DeleteTest.java

package zh.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import zh.hibernate.entity.User;
import zh.hibernate.utils.HibernateUtils;

/**
 * 删除操作:session.delete(对象)
 * @author ZH
 */
public class DeleteTest {

	public static void main(String[] args) {
		
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();// 开启事务
			// 先查询,再删除
			User user = session.load(User.class, 1);// 不发生查询语句
			session.delete(user);// 发送查询语句
			
			transaction.commit();// 提交事务,发送删除语句
		} catch (Exception e) {
			transaction.rollback();// 回滚事务
		} finally {
			session.close();// 关闭session
			sessionFactory.close();// 实际开发中,不需要关闭
		}

	}
	
}

删除前,


删除后,


9.实体类对象的三种状态

瞬时态:无id,与session无关联。

持久态:有id,与session有关联。

脱管态:有id,与session无关联。

10.一级缓存和二级缓存

【一级缓存】

1默认是打开的;

2使用范围是session创建到session关闭;

3一级缓存中存储的数据是持久态数据。

【二级缓存】

1)目前已经不使用了,被 redis代替;

2)默认不是打开的,需要配置;

3)使用范围是sessionFactory范围。

验证一级缓存的存在,

CacheDemo.java

package zh.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import zh.hibernate.entity.User;
import zh.hibernate.utils.HibernateUtils;

public class CacheDemo {

	public static void main(String[] args) {

		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();// 开启事务

			// 先在一级缓存中查询,如果没有,就向数据库发送查询语句;
			// 查询出的对象会保存在一级缓存和快照区中
			User user1 = session.get(User.class, 2);
			System.out.println(user1);

			// 先在一级缓存中查询,由于一级缓存中有,所以不向数据库发送查询语句
			User user2 = session.get(User.class, 2);
			System.out.println(user2);

			transaction.commit();// 提交事务
		} catch (Exception e) {
			transaction.rollback();// 回滚事务
		} finally {
			session.close();// 关闭session
			sessionFactory.close();// 实际开发中,不需要关闭
		}

	}

}

猜你喜欢

转载自blog.csdn.net/qq_41706150/article/details/80997255
今日推荐