Hibernate-基础入门案例,增删改查
项目结构:


数据库:
/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.5.53 : Database - hibernate01
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@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 SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_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>
Hibernate-基础入门案例,增删改查的更多相关文章
- MyBatis入门案例 增删改查
一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...
- hibernate关联对象的增删改查------查
本篇博客是之前博客hibernate关联对象的增删改查------查 的后继,本篇代码的设定都在前文已经写好,因此读这篇之前,请先移步上一篇博客 //代码片5 SessionFactory sessi ...
- Mybatis入门之增删改查
Mybatis入门之增删改查 Mybatis如果操作成功,但是数据库没有更新那就是得添加事务了.(增删改都要添加)----- 浪费了我40多分钟怀疑人生后来去百度... 导入包: 引入配置文件: sq ...
- get,post,put,delete四种基础方法对应增删改查
PUT,DELETE,POST,GET四种基础方法对应增删改查 1.GET请求会向数据库发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改.增加数 ...
- Hibernate入门案例 增删改
一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...
- Hibernate入门_增删改查
一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private ...
- Hibernate——(2)增删改查
案例名称:Hibernate完成增删改查 案例描述:抽取出工具类并完成删除.修改.查询功能. 具体过程: 1.使用上面的例子(Hibernate--(1)Hibernate入门http://blog. ...
- MySQL 之基础操作及增删改查等
一:MySQL基础操作 使用方法: 方式一: 通过图型界面工具,如 Navicat,DBeaver等 方式二: 通过在命令行敲命令来操作 SQL ( Structure query language ...
- Struts2+Spring+Hibernate实现员工管理增删改查功能(一)之ssh框架整合
前言 转载请标明出处:http://www.cnblogs.com/smfx1314/p/7795837.html 本项目是我写的一个练习,目的是回顾ssh框架的整合以及使用.项目介绍: ...
- hibernate关联对象的增删改查------增
本文可作为,北京尚学堂马士兵hibernate课程的学习笔记. 这一节,我们看看hibernate关联关系的增删改查 就关联关系而已,咱们在上一节已经提了很多了,一对多,多对一,单向,双向... 其实 ...
随机推荐
- 3.Java基础:String对象的创建和使用
一.常用的创建方式 String s1=”abc“: String s2=”abc“: s1==s2 ==> true 解析:s1和s2指向的是同一个字符串池地址 二.不常用的创建方式 S ...
- C# -- 等待异步操作执行完成的方式 C# -- 使用委托 delegate 执行异步操作 JavaScript -- 原型:prototype的使用 DBHelper类连接数据库 MVC View中获取action、controller、area名称、参数
C# -- 等待异步操作执行完成的方式 C# -- 等待异步操作执行完成的方式 1. 等待异步操作的完成,代码实现: class Program { static void Main(string[] ...
- mongodb win7 32位系统安装以及配置
今天安装 win7 32位系统 mongodb 费了好大劲..记录一下,希望相同的同学可以少踩点坑. 1.安装 我安装的是3.2.4 地址:http://downloads.mongodb.org/ ...
- pylot 学习笔记-使用
Console and Blocking Mode - Command Line Options: usage: run.py [options] args -a, --agents=NUM_AGEN ...
- mpu6050 DMP库的移植
https://www.amobbs.com/thread-5528472-1-1.html 官方的运动库,必须通过这个才能启用MPU6050的DMP引擎(数据手册里完全不提这个东西,必须在官网注册登 ...
- STM32 GPIO口模式配置
F103系列 typedef struct { uint16_t GPIO_Pin; /*!< Specifies the GPIO pins to be configured. This pa ...
- GM11灰色模型
作者:桂. 时间:2017-08-12 08:34:06 链接:http://www.cnblogs.com/xingshansi/p/7348714.html 前言 灰色模型(Gray model ...
- 在 IE 浏览器中,使用 bootstrap 使得页面滚动条浮动显示,自动隐藏,自动消失
貌似是从 IE10 开始?为了触屏操作优化浏览器的内容显示,IE 浏览器提供了一种可以浮动显示,自动隐藏的滚动条样式,但是这个样式会在某些情况下造成一些困扰,比如下图... 其实默认情况下,桌面版的 ...
- HTML5 CSS3 专题 :诱人的实例 3D旋转木马效果相冊
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/32964301 首先说明一下创意的出处:http://www.zhangxinxu ...
- linux工具大全
Linux Performance hi-res: observability + static + perf-tools/bcc (svg)slides: observabilityslides: ...