hibernate中简单的增删改查
项目的整体结构如下

1.配置文件
hibernate.cfg.xml
<!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="connection.url">jdbc:mysql://127.0.0.1:3306/diban</property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 将当前会话和线程绑定 -->
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 在配置文件中引入映射文件 -->
<mapping resource="cn/test/entity/product.hbm.xml"/>
</session-factory>
</hibernate-configuration>

2.映射文件
<!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="cn.test.entity.Product" table="`product`">
<id name="id" type="java.lang.Integer" column="`id`">
<generator class="assigned"></generator><!-- 由应用程序生成,即自己在程序中书写 -->
</id>
<property name="productName" type="java.lang.String" column="`product_name`"></property>
<property name="productInfo" type="java.lang.String" column="product_info"></property>
<property name="isno" type="java.lang.Integer" column="isno"></property>
<property name="productType" type="java.lang.Integer" column="product_type"></property>
<property name="productYuanjia" type="java.lang.Double" column="product_yuanjia "></property>
<property name="productPrice" type="java.lang.Double" column="product_price"></property>
<property name="productXinghao" type="java.lang.String" column="product_xinghao"></property>
<property name="guige" type="java.lang.String" column="guige"></property>
</class>
</hibernate-mapping>

3.实体类

4.例子
package cn.test.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 cn.test.entity.Product;
public class Test001 {
/**
* 新增
*/
@Test
public void Test002() {
Transaction tx = null;
try {
//1.读取并解析配置文件和映射文件
Configuration conf = new Configuration().configure();
//2.根据配置文件和映射文件中的信息,创建sessionFactory对象
SessionFactory factory = conf.buildSessionFactory();
//3.创建session对象
Session session = factory.openSession();
//4.开始一个事务(创建一个事物对象)
tx = session.beginTransaction();
//5.创建一个对象并且初始化
Product p = new Product();
p.setId(137);
p.setProductName("137");
//6.数据库操作使用sava方法将数据添加到数据库中
session.save(p);
//7.结束事物
tx.commit();
} catch (Exception e) {
e.printStackTrace();
//7.结束事物
if(tx != null)
tx.rollback();
}
}
/**
* 删除
*/
@Test
public void Test005() {
Transaction tx = null;
try {
Configuration conf = new Configuration().configure();
SessionFactory factory = conf.buildSessionFactory();
Session session = factory.openSession();
tx = session.beginTransaction();
Product p = new Product();
p.setId(138);
session.delete(p);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
}
}
/**
* updata更新的方法
* saveOrUpdata
* 先根据Id到数据库中判断是否有这条数据
* 如果有那么执行更新的方法
* 如果没有那么执行增加的方法
*/
@Test
public void Test004() {
Transaction tx = null;
try {
Configuration conf = new Configuration().configure();
SessionFactory factory = conf.buildSessionFactory();
Session session = factory.openSession();
tx = session.beginTransaction();
Product p = new Product();
p.setId(138);
p.setProductName("nimei111");
session.saveOrUpdate(p);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
}
}
/**
* 根据Id查询具体的某一条数据
* load 延迟加载
* 使用load方法时不会直接发动sql语句到数据库中查询具体的数据,而是会先得到一个只有id属性的代理对象,只有当使用到其他属性时才会发送
* sql语句到数据库中查询具体的数据
* get 不延迟加载
*/
@Test
public void Test003() {
Transaction tx = null;
try {
//1.读取并解析配置文件和映射文件
Configuration conf = new Configuration().configure();
//2.根据配置文件和映射文件的信息创建会话工厂
SessionFactory factory = conf.buildSessionFactory();
//3.通过会话工厂打开session对象
Session session = factory.openSession();
//4.通过session对象创建事物对象
tx = session.beginTransaction();
//5.根据对象Id查询指定的单条对象数据
//Product p = (Product) session.load(Product.class, 137);
Product p = (Product)session.get(Product.class, 137);
System.out.println(p.getId());
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
}
}
/**
* ------------hql
*
* 查询语法
* 1.from子句
* from Product #查询所有的Product(查询所有属性)
* 2.select子句
* select Product.id from Product 查询所有Product的id(只查询id)
* 3.where
* from Product where id = 'haha'
* from Product where productName is not null
* 4.使用表达式
* from Product where lower(productName) = 'hhh'
* lower()函数用于把字符串中的每个字母改为小写
* from Product where year(createDate) = 1980
* year()函数用于获取日期字段的年份
*
*
* 如何为sql语句传入参数:
* 1.拼接字符串
* 2.参数绑定
* 1>.按位置绑定参数
* 2>.按名称绑定参数
* 3>.将数据封装到对象中绑定参数
* 如 : from Product where id = :id and productName = :name
* Product p = new Product();
* p.setId(11);
* p.setProductName("hello");
* query.setProperties(p);
*
*/
/**
* 拼接字符串
*/
@Test
public void Test006() {
String id = "id";
String hql = "from Product order by "+id;
Configuration conf = new Configuration().configure();
Session session = conf.buildSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
List<Product> proList = query.list();
for (Product product : proList) {
System.out.println(product.getId()+":"+product.getProductName());
}
}
/**
* 按位置绑定参数
*/
@Test
public void Test007() {
String hql = "from Product order by ?";
Configuration conf = new Configuration().configure();
Session session = conf.buildSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
query.setString(0, "id");
List<Product> proList = query.list();
for (Product product : proList) {
System.out.println(product.getId()+":"+product.getProductName());
}
}
/**
* 按名称绑定参数
*/
@Test
public void Test008() {
String hql = "from Product order by :id";
Configuration conf = new Configuration().configure();
Session session = conf.buildSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
query.setString("id", "id");
List<Product> proList = query.list();
for (Product product : proList) {
System.out.println(product.getId()+":"+product.getProductName());
}
}
/**
* 分页查询
* setFirstResult((当前页-1)*页面容量)
* setmaxResults(页面容量)
*/
@Test
public void Test009() {
String hql = "from Product order by id";
Configuration conf = new Configuration().configure();
Session session = conf.buildSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
query.setFirstResult((1-1)*9); //指定从第几条数据开始查询
query.setMaxResults(9); //指定页面容量(也就是每页显示的多少条数据)
List<Product> proList = query.list();
for (Product product : proList) {
System.out.println(product.getId()+":"+product.getProductName());
}
}
}
hibernate中简单的增删改查的更多相关文章
- 数据库中简单的增删改查(CRUD)
一切都是基于数据,而对数据的管理都离不开数据库.最近学到数据库的简单操作,所以写下这篇文章,总结一下学习到的知识.浅陋之处,多多见谅. 补充一下:一直弄不清SQL Server,Mysql ,以及Or ...
- 用CI框架向数据库中实现简单的增删改查
以下代码基于CodeIgniter_2.1.3版 用PHP向数据库中实现简单的增删改查(纯代码)请戳 http://www.cnblogs.com/corvoh/p/4641476.html Code ...
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- salesforce 零基础学习(五十一)使用 Salesforce.com SOAP API 实现用户登录以及简单的增删改查(JAVA访问salesforce)
此篇请参看:https://resources.docs.salesforce.com/202/latest/en-us/sfdc/pdf/salesforce_developer_environme ...
- 通过JDBC进行简单的增删改查
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- 初试KONCKOUT+WEBAPI简单实现增删改查
初试KONCKOUT+WEBAPI简单实现增删改查 前言 konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作.Kn ...
- MVC3.0+knockout.js+Ajax 实现简单的增删改查
MVC3.0+knockout.js+Ajax 实现简单的增删改查 自从到北京入职以来就再也没有接触MVC,很多都已经淡忘了,最近一直在看knockout.js 和webAPI,本来打算采用MVC+k ...
- SpringMVC之简单的增删改查示例(SSM整合)
本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...
- hibernate关联对象的增删改查------查
本篇博客是之前博客hibernate关联对象的增删改查------查 的后继,本篇代码的设定都在前文已经写好,因此读这篇之前,请先移步上一篇博客 //代码片5 SessionFactory sessi ...
随机推荐
- Centos 安装 mysql 5.7
下载mysql yum包 wget http://repo.mysql.com/mysql57-community-release-el7-10.noarch.rpm 安转软件源 xxx.rpm是刚刚 ...
- 九、Appium-python-UI自动化之通过text定位
1.通过xpath定位text xpath路径为://android.widget.EditText[@text='请输入包含街道的完整地址'] 2.通过AndroidUIAutomator # 这个 ...
- IPSec的高可用性技术
IPSec VPN的高可用性技术:①.DPD(Dead Peer Detection)对等体检测 ——旨在检查有问题的IPSec VPN网络,并快速的切换到备 ...
- Cisco AP-如何识别思科胖瘦AP
思科的胖瘦AP识别的方式不止一种,这里简单的总结一些我了解到的方式: 1.根据思科AP的型号 这个和思科不同时期的产品有关系,老一点的和新一些的AP命名上存在差别,这里简单举例: 类型1:AIR-LA ...
- 洛谷P1346 电车(需要稍加思索的最短路)
题目描述 在一个神奇的小镇上有着一个特别的电车网络,它由一些路口和轨道组成,每个路口都连接着若干个轨道,每个轨道都通向一个路口(不排除有的观光轨道转一圈后返回路口的可能).在每个路口,都有一个开关决定 ...
- BGR 与 HSV 模式的转换规则
HSV模式中的H.S.V分别表示色调.饱和度.亮度 RGB转化到HSV的算法:max=max(R,G,B) min=min(R,G,B) if R = max, H = (G-B)/(max-min) ...
- RestTemplate post请求使用map传参 Controller 接收不到值的解决方案 postForObject方法源码解析.md
结论 post方法中如果使用map传参,需要使用MultiValueMap来传递 RestTemplate 的 postForObject 方法有四个参数 String url => 顾名思义 ...
- Centos 下安装php
1 从php 官网下载源安装包 http://php.net/downloads.php // 安装php 扩展 2 yum install libxml2 libxml2-devel openssl ...
- UINavigationController+FDFullscreenPopGesture全屏回滑手势阅读理解
滑动返回纯oc.纯swifthttps://github.com/Bonway/BBGestureBack UINavigationController+FDFullscreenPopGesture全 ...
- twisted 模拟scrapy调度循环
"""模拟scrapy调度循环 """from ori_test import pr_typeimport loggingimport ti ...