一个完整的hibernate例子

1 。建立数据库
drop database if exists SAMPLEDB;
create database hello;
use hello;

create table CUSTOMERS (
  ID int not null primary key,
  NAME varchar(15) not null,
  PASSWORD varchar(8) not null, 
 
);

2。在eclipse 中新建工程hbtest

3。在src中新建package hbm

4。新建pojo类Customer

package hbm;

public class Customer {
    private int id;
    private String name;
    private String password;
    /**
     * @return Returns the id.
     */
    public int getId() {
        return id;
    }
    /**
     * @param id
     *            The id to set.
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return Returns the name.
     */
    public String getName() {
        return name;
    }
    /**
     * @param name
     *            The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return Returns the password.
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param password
     *            The password to set.
     */
    public void setPassword(String password) {
        this.password = password;
    }
    //constructor
    public Customer() {
    }

}

5。使用myeclipse插件建立hibernate.cfg.xml   位于src目录下
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    <property name="connection.username">root</property>
    <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hello</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="myeclipse.connection.profile">hbmysql</property>
    <property name="connection.password">123</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <mapping resource="hbm/Customer.hbm.xml" />

</session-factory>

</hibernate-configuration>

6。在hbm package内新建Customer.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-mapping>
<class name="hbm.Customer" table="CUSTOMERS">
<id name="id" column="ID" type="int">
<generator class="increment"/>
</id>
<property name="name" column="NAME" type="string" not-null="true"/>
<property name="password" column="PASSWORD" type="string" not-null="true"/>
</class>

</hibernate-mapping>

7。使用hibernate操作数据库
package hbm;

import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.Iterator;
import java.util.List;

public class Hbmain {

    public static SessionFactory sessionFactory;//数据存储源
    static {
        try {
            Configuration config = new Configuration().configure();
            sessionFactory = config.buildSessionFactory();

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

    /*
     * 将一个customer对象存入database
     * @Customer customer Object
     */
    public void saveCustomer(Customer ct) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(ct);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    /*
     * 查找所有的customer object
     */
    public void findAll() {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            List customers = session.createQuery(
                    "from Customer as c order by c.name asc").list();
            Iterator it = customers.iterator();
            System.out.println("append:"+customers.size());
            while(it.hasNext())
            {
                Customer c = (Customer)it.next();
                System.out.println("ID:" + c.getId());
                System.out.println("Name:" + c.getName());
                System.out.println("Pass:" + c.getPassword());
            }
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
        }

    }

    /*
     * 修改customer Name
     * @name
     */
    public void loadUpdate(int customer_id, String name) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Customer c = (Customer) session.load(Customer.class, customer_id);
            c.setName(name);
            tx.commit();

        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();

        } finally {
            session.close();
        }

    }
  
    /*
     * 测试以上的方法
     * save() find() update()
     */
   
    public void test()
    {
        Customer ct = new Customer();
        //ct.setId(5);
        ct.setName("buaa");
        ct.setPassword("5768");
        this.saveCustomer(ct);
        this.findAll();
        this.loadUpdate(ct.getId(),"phop");
    }
   
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Hbmain hb = new Hbmain();
        hb.test();
        sessionFactory.close();

    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值