---
title: "hibernate3 简单的 CRUD 示例"
author: "X_boy"
date: "2011-10-04T01:37:34Z"
tags: []
categories: ["编程语言"]
slug: "hibernate3-crud"
draft: false
lastmod: "2011-10-04T01:37:59Z"
id: 1185083
url: "https://x-boy.iteye.com/blog/1185083"
---

CRUD是指在做计算处理时增加、查询、更新和删除几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能。下面示例演示了如何创建session实例，并使用session的相关方法，实现对数据库表记录的添加。修改。删除和查找。

 

 1、 首先登录MySQL数据库，建立表box，SQL语句如下：

   create table box(

              id int(11) not null auto\_increment,

              width float default null,

              length float default null,

              height float default null,

              name   varchar(20) default null,

              primary key(id));

 

2、 Hibernate 配置文件hibernate.cfg.xml

 

   &lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE hibernate-configuration PUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt;

&lt;hibernate-configuration&gt;

&lt;session-factory&gt;

&lt;property name="connection.driver\_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;

&lt;property name="connection.url"&gt;jdbc:mysql://localhost:3306/hibernate&lt;/property&gt;

&lt;property name="connection.useUnicode"&gt;true&lt;/property&gt; 

       &lt;property name="connection.characterEncoding"&gt;UTF-8&lt;/property&gt;

&lt;property name="connection.username"&gt;root&lt;/property&gt;

&lt;property name="connection.password"&gt;mysql&lt;/property&gt;

&lt;property name="hibernate.c3p0.max\_size"&gt;20&lt;/property&gt;

&lt;property name="hibernate.c3p0.min\_size"&gt;1&lt;/property&gt;

&lt;property name="hibernate.c3p0.timeout"&gt;5000&lt;/property&gt;

&lt;property name="hibernate.c3p0.max\_statements"&gt;100&lt;/property&gt;

&lt;property name="hibernate.c3p0.idle\_test\_period"&gt;3000&lt;/property&gt;

&lt;property name="hibernate.c3p0.acquire\_increment"&gt;2&lt;/property&gt;

&lt;property name="hibernate.c3p0.validate"&gt;true&lt;/property&gt;

&lt;property name="dialect"&gt;org.hibernate.dialect.MySQLInnoDBDialect&lt;/property&gt;

&lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;

 

&lt;mapping resource="crud/Box.hbm.xml"/&gt;

&lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;

 

3、Java 对应的类Box.java

 

 

package crud;

 

public class Box {

private Integer id;

private float width;

private float length;

private float height;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public float getWidth() {

return width;

}

public void setWidth(float width) {

this.width = width;

}

public float getLength() {

return length;

}

public void setLength(float length) {

this.length = length;

}

public float getHeight() {

return height;

}

public void setHeight(float height) {

this.height = height;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

 

}

 

4、Box类的配置文件box.hbm.xml

 

 

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE hibernate-mapping PUBLIC

        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"&gt;

&lt;hibernate-mapping&gt;

      &lt;class name="crud.Box" table="box"&gt;

            &lt;id name="id" type="java.lang.Integer"&gt;

            &lt;column name="id"/&gt;

            &lt;generator class="native"/&gt;

            &lt;/id&gt;

 

            &lt;property name="width" type="java.lang.Float"&gt;

            &lt;column name="width" precision="12" scale="0"/&gt;

            &lt;/property&gt;

 

            &lt;property name="length" type="java.lang.Float"&gt;

            &lt;column name="length" precision="12" scale="0"/&gt;

            &lt;/property&gt;

 

            &lt;property name="height" type="java.lang.Float"&gt;

            &lt;column name="height" precision="12" scale="0"/&gt;

            &lt;/property&gt;

 

            &lt;property name="name" type="java.lang.String"&gt;

            &lt;column name="name" length="20"/&gt;

            &lt;/property&gt;

      &lt;/class&gt;

&lt;/hibernate-mapping&gt;

   至此，第一个Hibernate应用就完成了，下面编写一个测试程序，实现box的CRUD操作。Text.java文件

1、增加记录-&gt;session.save()

 

 

public class text {

public static void main(String\[] args){

Configuration config = new Configuration().configure();

SessionFactory sf = config.buildSessionFactory();

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

             

                Box box = new Box();

                box.setHeight(24.3f);

                box.setLength(100.00f);

                box.setWidth(45.00f);

                box.setName("Mybox");

                session.save(box);

                tx.commit();

                session.close();

   }

}

2、按条件（name）查找数据库存中的记录 -&gt;session.createQuery()，并将其删除 -&gt;session.delete()

package crud;

import java.util.List;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

public class text {

public static void main(String\[] args){

Configuration config = new Configuration().configure();

SessionFactory sf = config.buildSessionFactory();

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

        Box box = new Box();

       @SuppressWarnings("rawtypes")

                //查找数据库中的数据

List result = session.createQuery("from Box").list();

for(int i=0;i&lt;result.size();i++){

box = (Box) result.get(i);

if(box.getName().equals("Mybox")){

break;

}

}

             //显示数据库中name=“Mybox”的记录

     System.out.println(box.getId()+" "+box.getHeight()+" "+box.getLength()+" "+box.getWidth());

    

            //删除记录

   session.delete(box);

       

   tx.commit();

    session.close();

}

}

3、按条件（name)查找数据库中的记录-&gt;session.createQuery(),并将其更改，即更新记录session.update();

package crud;

import java.util.List;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

public class text {

public static void main(String\[] args){

Configuration config = new Configuration().configure();

SessionFactory sf = config.buildSessionFactory();

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

        Box box = new Box();

       @SuppressWarnings("rawtypes")

List result = session.createQuery("from Box").list();

for(int i=0;i&lt;result.size();i++){

box = (Box) result.get(i);

if(box.getName().equals("Mybox")){

break;

}

}

    box.setName("Mybox\_1");//更改数据

   session.update(box);       //更新数据

   tx.commit();

            session.close();

}

}