hibernate helloword

来源:互联网 发布:塌鼻子 知乎 编辑:程序博客网 时间:2024/05/31 19:41

1.首先下载hibernate 对应的jar 包

antlr-2.7.6.jar commons-collections-3.1.jar dom4j-1.6.1.jar hibernate3.jar javassist-3.9.0.GA.jar jta-1.1.jar log4j-1.2.15.jar mysql-connector-java-5.1.9.jar

slf4j-api-1.5.8.jar slf4j-log4j12-1.6.4.jar

其中mysql-connector-java-5.1.9.jar 为连接数据库驱动包

slf4j-api-1.5.8.jar slf4j-log4j12-1.6.4.jar log4j-1.2.15.jar 日志接口包与实现包

2.数据库为mysql IDE eclipse 

3.新建数据库

(1)在mysql bin下 进入数据库 mysql -uroot -p ;

(2)create database hibernate;

(3)mysql> create table customers( id int primary key,name varchar(15) not null,password varchar(8) not null);

4.在src 跟目录下新建hibernate.cfg.xml 文件

文件内容如下:

<?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">

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

注意:这里用的是mysql 方言。

5.新建hbm包

(1)Customer 类

package hbm;

public class Customer {
    private int id;
    private String name;
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Customer() {
    }
}

(2)Customer.hbm.xml 对应Customer类的于数据库的配置文件

<?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">

<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>

(3)测试类Hbmain.java

package hbm;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
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("wj");
        ct.setPassword("123456");
        this.saveCustomer(ct);
        this.findAll();
        this.loadUpdate(ct.getId(), "phop");
    }

    public static void main(String[] args) {
        Hbmain hb = new Hbmain();
        hb.test();
        sessionFactory.close();
    }

}