hibernate database connection and basic operation of the data

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_36940806/article/details/86707760

First, preparation

1. Download the relevant hibernate jar package

2.mysql or oracle database

Second, the project to build

1. Create a new project and import java hibernate relevant jar package ( http://hibernate.org/orm/releases/5.4/ ) and a corresponding database-driven package

2. Create a hibernate under the project src directory configuration file named  hibernate.cfg.xml  configuration information for the database connection

Note: Here After After configuration, database entity class will automatically generate a corresponding table, without having to manually create tables

<?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 元素用于配置Hibernate中的属性 键:值 -->
		<!-- hibernate.connection.driver_class : 连接数据库的驱动 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

		<!-- hibernate.connection.username : 连接数据库的用户名 -->
		<property name="hibernate.connection.username">root</property>

		<!-- hibernate.connection.password : 连接数据库的密码 -->
		<property name="hibernate.connection.password">a</property>

		<!-- hibernate.connection.url : 连接数据库的地址,路径 -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>

		<!-- show_sql: 操作数据库时,会 向控制台打印sql语句 -->
		<property name="show_sql">true</property>

		<!-- format_sql: 打印sql语句前,会将sql语句先格式化 -->
		<property name="format_sql">true</property>

		<!-- hbm2ddl.auto: 生成表结构的策略配置 update(最常用的取值): 如果当前数据库中不存在表结构,那么自动创建表结构. 
			如果存在表结构,并且表结构与实体一致,那么不做修改 如果存在表结构,并且表结构与实体不一致,那么会修改表结构.会保留原有列. 
			create(很少):无论是否存在表结构.每次启动Hibernate都会重新创建表结构.(数据会丢失) 
			create-drop(极少): 无论是否存在表结构.每次启动Hibernate都会重新创建表结构.每次Hibernate运行结束时,删除表结构. 
			validate(很少):不会自动创建表结构.也不会自动维护表结构.Hibernate只校验表结构. 如果表结构不一致将会抛出异常. -->
		<property name="hbm2ddl.auto">update</property>

		<!-- 数据库方言配置 org.hibernate.dialect.MySQLDialect (选择最短的) -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- hibernate.connection.autocommit: 事务自动提交 -->
		<property name="hibernate.connection.autocommit">true</property>

		<!-- 将Session与线程绑定=> 只有配置了该配置,才能使用getCurrentSession -->
		<property name="hibernate.current_session_context_class">thread</property>

		<!-- 引入ORM 映射文件 填写src之后的路径 -->
		<mapping resource="com/hibernate/pojo/product.hbm.xml" />
	</session-factory>
</hibernate-configuration>

3. The entity class  Product 

package com.hibernate.pojo;

import java.io.Serializable;

public class Product implements Serializable {

	private static final long serialVersionUID = -366926015333601797L;
	private Integer id; // 唯一标志符
	private String name; // 产品名称
	private Double price; // 价格
	private String factory;// 生产商
	private String remark; // 备注

	public Product() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Product(Integer id, String name, Double price, String factory, String remark) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.factory = factory;
		this.remark = remark;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	public String getFactory() {
		return factory;
	}

	public void setFactory(String factory) {
		this.factory = factory;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	@Override
	public String toString() {
		return "Product [id=" + id + ", name=" + name + ", price=" + price + ", factory=" + factory + ", remark="
				+ remark + "]";
	}

}

4. Mapping File Entity   Product.hbm.xml  (Note: In naming rules .hbm.xml end)

<?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="com.hibernate.pojo.Product" table="tb_product">
		<id name="id" column="id" type="int">
			<!-- 此处定义主键生成策略:native(根据底层数据库对自动从生成标志符的支持能力选择identity,sequence或hilo) -->
			<generator class="native" />
		</id>
		<property name="name" type="string" not-null="true" length="50">
			<column name="name" ></column>
		</property>
		<property name="price" type="double" not-null="true">
			<column name="price" ></column>
		</property>
		<property name="factory" type="string" not-null="true"
			length="50">
			<column name="factory" ></column>
		</property>
		<property name="remark" type="string" not-null="true" length="50">
			<column name="remark" ></column>
		</property>
	</class>
</hibernate-mapping>

5. Obtain the session tools    HibernateUtil

Here the use of ThreadLocal save session, ThreadLocal to hold a thread shared variables: for the same static ThreadLocal,
different from the thread can only get, set, remove your own variables, variables without affecting other threads, to avoid the multi-threaded shared data problems.

package com.hibernate.util;

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

public class HibernateUtil {
	// ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,
	// 不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量,避免了多线程共享数据的问题。
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static SessionFactory sessionFactory = null; // sessionFactory对象
	// 获取sessionFactory

	static {
		try {
			// 加载hibernate配置文件(默认加载classpath根目录下的hibernate.cfg.xml)
			Configuration cfg = new Configuration().configure();
			sessionFactory = cfg.buildSessionFactory();// 创建sessionFactory对象
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取session
	 * 
	 * @return
	 * @throws HibernateException
	 */

	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) { // session为空或session关闭
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			threadLocal.set(session);
		}

		return session;
	}

	/**
	 * 重建会话工厂
	 */
	public static void rebuildSessionFactory() {
		try {
			Configuration cfg = new Configuration().configure();// 加载hibernate配置文件
			sessionFactory = cfg.buildSessionFactory();// 创建sessionFactory对象
		} catch (HibernateException e) {
			System.err.println("创建会话工厂失败...");
			e.printStackTrace();
		}
	}

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

	/**
	 * 关闭session
	 */
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close();
		}
	}

}

6. interact with a database, check the additions and deletions to achieve change  ProductDao 

package com.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.hibernate.pojo.Product;
import com.hibernate.util.HibernateUtil;

public class ProductDao {

	/**
	 * 添加
	 * 
	 * @param product
	 */
	public void add(Product product) {
		Session session = null;// 声明session对象
		// hibernate的持久化操作
		try {
			session = HibernateUtil.getSession();// 获取session
			session.beginTransaction();// 开启事务
			session.save(product);// 执行数据库添加操作
			session.getTransaction().commit();// 提交事务
			System.out.println("数据添加成功...");
		} catch (HibernateException e) {
			session.getTransaction().rollback();// 回滚
			System.err.println("数据添加失败!");
			e.printStackTrace();
		} finally {
			HibernateUtil.closeSession();// 关闭session对象
		}
	}

	/**
	 * 查询
	 * 
	 * @param id
	 */
	public void select(Integer id) {
		Session session = null;// 声明session对象
		// hibernate的持久化操作
		try {
			session = HibernateUtil.getSession();// 获取session
			Product product = (Product) session.get(Product.class, id);// 根据id查询,装载product对象
			System.out.println("查询结果: " + product);
		} catch (HibernateException e) {
			System.err.println("数据查询失败!");
			e.printStackTrace();
		} finally {
			HibernateUtil.closeSession();// 关闭session对象
		}
	}

	/**
	 * 删除
	 * 
	 * @param id
	 */
	public void delete(Integer id) {
		Session session = null;// 声明session对象
		// hibernate的持久化操作
		try {
			session = HibernateUtil.getSession();// 获取session
			Product product = (Product) session.get(Product.class, id);// 根据id装载product对象
			session.delete(product); // 删除持久化对象
			session.flush();// 强制刷新提交
			System.out.println("已成功删除id为: " + product.getId()+"的信息!");
		} catch (HibernateException e) {
			System.err.println("数据删除失败!");
			e.printStackTrace();
		} finally {
			HibernateUtil.closeSession();// 关闭session对象
		}
	}

	/**
	 * 修改
	 * 
	 * @param product
	 */
	public void update(Product newProduct) {
		Session session = null;// 声明session对象
		// hibernate的持久化操作
		try {
			session = HibernateUtil.getSession();// 获取session
			Product product = (Product) session.get(Product.class, newProduct.getId());// 根据id装载product对象
			product.setRemark(newProduct.getRemark());
			session.flush();// 强制刷新提交
			System.out.println("数据修改成功...");
		} catch (HibernateException e) {
			System.err.println("数据修改失败!");
			e.printStackTrace();
		} finally {
			HibernateUtil.closeSession();// 关闭session对象
		}
	}

}

7. The unit test classes  Producttest  (on the right-click approach requires to run)

package com.hibernate.test;

import org.junit.Before;
import org.junit.Test;

import com.hibernate.dao.ProductDao;
import com.hibernate.pojo.Product;

public class ProductTest {
	ProductDao productDao = null;

	@Before
	public void init() {
		productDao = new ProductDao();
	}

	@Test
	public void addTest() {

		Product product = new Product();
		product.setName("Hibernate初级");
		product.setPrice(78.0);
		product.setFactory("ByVean");
		product.setRemark("无");
		productDao.add(product); // 添加操作
	}

	@Test
	public void selectTest() {
		productDao.select(1);// 查询操作(根据id查)
	}

	@Test
	public void updateTest() {
		Product product = new Product();
		product.setId(1); //需要修改的id
		product.setRemark("已修改"); //修改指定属性
		productDao.update(product);
	}

	@Test
	public void deleteTest() {
		productDao.delete(1);// 删除操作(根据id删)
	}
}

Third, the operating results

1. Add operation

Print Console Information

Database Information

2. Find operation

Print Console Information

3. Modify Operation

Print Console Information

Database Information

4. Delete operation

Print Console Information

Database Information

Guess you like

Origin blog.csdn.net/qq_36940806/article/details/86707760