Hibernate-基础入门案例,增删改查

项目结构:

数据库:

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.5.53 : Database - hibernate01
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=‘‘*/;

/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`hibernate01` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `hibernate01`;

/*Table structure for table `customer` */

DROP TABLE IF EXISTS `customer`;

CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Data for the table `customer` */

insert  into `customer`(`id`,`name`,`age`) values (1,‘张三‘,20),(2,‘王五‘,22),(3,‘赵六‘,29);

/*!40101 SET [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
/*!40014 SET [email protected]_UNIQUE_CHECKS */;
/*!40111 SET [email protected]_SQL_NOTES */;

所使用的jar包:

1、导入hibernate核心必须包(\lib\required)

2、导入mysql驱动包

3、导入log4j日志包

项目代码:

com.gordon.domain:

--Customer.java

package com.gordon.domain;

public class Customer {

	private Integer id;
	private String name;
	private Integer age;

	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 Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + ", age=" + age + ", getId()=" + getId() + ", getName()="
				+ getName() + ", getAge()=" + getAge() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
				+ ", toString()=" + super.toString() + "]";
	}
}

--Customer.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.gordon.domain.Customer" table="customer">
		<id name="id" column="id">
			<generator class="native"></generator>
		</id>
		<property name="name" column="name" />
		<property name="age" column="age" />
	</class>
</hibernate-mapping>

*Hibernate的删除/更新,要先根据id或者相应字段查询出数据,才能通过update/delete方法更新或者移除数据,自己构造对象进项操作则会报错。

com.gordon.test:*测试时需导入jUnit4测试包,然后可以在方法上双击选中方法名,右键 runas 运行在junit。

--Testhibernate.java

package com.gordon.test;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.gordon.domain.Customer;
import com.gordon.utils.HibernateUtil;

public class TestHibernate {

	/**
	 * 存储一条数据
	 */
	@Test
	public void testSave() {
		Configuration configuration = new Configuration().configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();

		Customer customer = new Customer();
		customer.setName("测试");
		customer.setAge(22);

		try {
			session.save(customer);
			tr.commit();
		} catch (Exception e) {
			tr.rollback();
			e.printStackTrace();
		}

		session.close();
	}

	/**
	 * 删除一条数据
	 */
	@Test
	public void testDelete() {
		Configuration configuration = new Configuration().configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();

		Customer customer = null;

		try {

			customer = session.get(Customer.class, 4);

			session.delete(customer);

			tr.commit();
		} catch (Exception e) {
			tr.rollback();
			e.printStackTrace();
		}

		session.close();
	}

	/**
	 * 修改一条数据
	 */
	@Test
	public void testUpdate() {
		Configuration configuration = new Configuration().configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();

		Customer customer = null;

		try {

			customer = session.get(Customer.class, 1);
			customer.setName("jack");

			session.update(customer);

			tr.commit();
		} catch (Exception e) {
			tr.rollback();
			e.printStackTrace();
		}

		session.close();
	}

	/**
	 * 获取多条数据,查询可以不使用事务
	 */
	@SuppressWarnings("unchecked")
	@Test
	public void testGetAll() {
		Session session = HibernateUtil.getSession();

		List<Customer> customers = null;

		try {

			Query query = session.createQuery("from Customer");
			customers = query.list();

		} catch (Exception e) {
			e.printStackTrace();
		}

		session.close();

		for (Customer customer : customers) {
			System.out.println(customer);
		}
	}

	/**
	 * 获取一条数据,查询可以不使用事务
	 */
	@Test
	public void testGet() {
		Session session = HibernateUtil.getSession();

		Customer customer = null;

		try {

			customer = session.get(Customer.class, 1);

		} catch (Exception e) {
			e.printStackTrace();
		}

		session.close();

		System.out.println(customer);
	}
}

com.gordon.utils:

--Hibernate.Util.java

package com.gordon.utils;

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

public class HibernateUtil {
	private static final Configuration CONFIGURATION;
	private static final SessionFactory SESSIONFACTORY;

	static {
		CONFIGURATION = new Configuration().configure();
		SESSIONFACTORY = CONFIGURATION.buildSessionFactory();
	};

	public static Session getSession() {
		return SESSIONFACTORY.openSession();
	}
}

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/hibernate01</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<mapping resource="com/gordon/domain/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>
时间: 2024-10-12 14:12:24

Hibernate-基础入门案例,增删改查的相关文章

MyBatis入门案例 增删改查

一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybat

Mybatis简单的入门之增删改查

一般的步骤如下 1.添加Mybatis所需要的包,和连接数据库所需的包 2.配置mybatis-config.xml文件 3.配置与pojo对应的映射文件 mybatis-config,xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http:/

Struts2+Hibernate+Spring框架实现增删改查

一.添加3个框架的JAR包,完成后写配置文件: 1.web配置文件: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation=&quo

hibernate关联对象的增删改查------查

本篇博客是之前博客hibernate关联对象的增删改查------查 的后继,本篇代码的设定都在前文已经写好,因此读这篇之前,请先移步上一篇博客 //代码片5 SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); session.beginTransa

Mybatis入门之增删改查

Mybatis入门之增删改查 导入包: 引入配置文件: sqlMapConfig.xml(mybatis的核心配置文件).log4j.properties(日志记录文件) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.or

Hibernate入门_增删改查

一.Hibernate入门案例剖析:  ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private Integer age; private String name; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public Integer getAge()

Hibernate入门案例 增删改

一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private Integer age; private String name; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public Integer getAge() {

TP5学习基础一:增删改查小demo

①TP5--增删改查简单的demo 我先吐槽一下:因为工作需要研究tp5,去官网看了一下哎呦,资源挺多挺全啊!然后下载唯一免费的官方教程,我曹pdf打开533页.讲的很细但是开发能等看完才做吗?看到精简版快速入门的还软妹币20试读3章.寻思找个demo案例吧,要不加群拿源码,要不视频教程收费.特喵的框架是开源的但是教程是收费的.寻思去论坛看看问题,不是我喷好多技术小白的问题,我想看看怎么获取传参传值,泥煤那个系统变量是什么鬼?挣扎了3个小时我放弃了官网.在度娘上找到一个demo,吭哧吭哧啃完.一

MySQL 之基础操作及增删改查等

一:MySQL基础操作 使用方法: 方式一: 通过图型界面工具,如 Navicat,DBeaver等 方式二: 通过在命令行敲命令来操作 SQL ( Structure query language ) 结构化查询语言 SQL语言分为4个部分:DDL(定义).DML(操作).DQL(查询).DCL(控制) 1.DDL语句 数据库定义语言: 数据库.表.视图.索引.存储过程,例如CREATE DROP ALTER 2.DCL语句 数据库控制语言: 例如控制用户的访问权限GRANT.REVOKE 3

Hibernate进行对象的增删改查

首先我们看看hibernate手动配置步骤 (这个了解一点就可以了,以后是不会自己全部手动配置的) 1.    创建WEB项目 2       下载hibernate-release-4.3.11.Final.zip,并解压. 3       将hibernate必须的包加入lib 4        打开hibernate-release-4.3.11.Final\lib\required文件夹,导入jar文件: 5       打开hibernate-release-4.3.11.Final\