hibernate连接数据库并实现对数据的基本操作

一,前期准备

1.下载hibernate相关jar包

2.mysql或者oracle数据库

二,项目搭建

1.新建java项目并导入hibernate相关jar包(http://hibernate.org/orm/releases/5.4/)及对应数据库驱动包

2.项目src目录下创建hibernate的配置文件 名为 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 元素用于配置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. 实体类 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.实体类映射文件  product.hbm.xml (注意:命名规则以  .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="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. 获取 session的工具类   HibernateUtil

这里采用 ThreadLocal保存session,ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,
不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量,避免了多线程共享数据的问题。

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.和数据库进行交互,实现增删查改 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.单元测试类 ProductTest  (在需要执行的方法上右击运行即可)

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删)
	}
}

三,运行结果

1.添加操作

控制台打印信息

数据库信息

2.查找操作

控制台打印信息

3.修改操作

控制台打印信息

数据库信息

4.删除操作

控制台打印信息

数据库信息

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用 Hibernate 连接数据库需要进行以下步骤: 1. 添加 Hibernate 依赖库到项目中。 2. 配置 Hibernate 的配置文件(hibernate.cfg.xml)。 3. 定义数据表与 Java 类之间的映射关系(通过 Hibernate 的注解或者 XML 映射文件)。 4. 编写 Java 代码调用 Hibernate API 进行 CRUD 操作。 下面是一个简单的 Hibernate 连接 MySQL 数据库的示例: 1. 添加 Hibernate 依赖库到项目中: 在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖: ``` <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.30.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> </dependencies> ``` 2. 配置 Hibernate 的配置文件(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.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?serverTimezone=UTC</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property> <property name="hibernate.show_sql">true</property> <mapping class="com.example.User"/> </session-factory> </hibernate-configuration> ``` 3. 定义数据表与 Java 类之间的映射关系: 可以使用注解方式或者 XML 映射文件的方式进行映射。 使用注解方式的示例: ``` @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; // 省略 getter 和 setter 方法 } ``` 4. 编写 Java 代码调用 Hibernate API 进行 CRUD 操作: ``` // 加载 Hibernate 配置文件 Configuration configuration = new Configuration().configure(); // 创建 SessionFactory SessionFactory sessionFactory = configuration.buildSessionFactory(); // 创建 Session Session session = sessionFactory.openSession(); // 开启事务 Transaction transaction = session.beginTransaction(); // 新增用户 User user = new User(); user.setName("张三"); user.setAge(20); session.save(user); // 提交事务 transaction.commit(); // 关闭 Session session.close(); // 关闭 SessionFactory sessionFactory.close(); ``` 以上代码实现了向数据库中插入一条数据的操作,其他的 CRUD 操作也类似。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赴前尘

喜欢我的文章?请我喝杯咖啡吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值