`
Ydoing
  • 浏览: 100953 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Hibernate入门与实例

 
阅读更多

Hibernate是一种ORM(对象关系/关系数据库)框架,其简单概念就是将Java中的对象映射为关系数据库中的表。程序员只需要操作Java中的对象,即只关心业务逻辑操作,Hibernate就会自动将业务逻辑操作翻译为底层SQL语句进行处理,程序员无需关系数据库中的操作。

首先建立POJO对象,这个对象将映射数据库中的表Employee:

package com.ydoing.domain;
public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private int salary;
    public Employee() {
    }
    public Employee(String fname, String lname, int salary) {
        this.firstName = fname;
        this.lastName = lname;
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String first_name) {
        this.firstName = first_name;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String last_name) {
        this.lastName = last_name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
} 

然后建立java对象与关系数据库中的表的关系,用Employee.hbm.xml来描述,放在src目录下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping package="com.ydoing.domain">
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping> 

还需要告诉Hibernate数据库的信息,用hibernate.cfg.xml描述,放在src目录下::

<?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.dialect">
            org.hibernate.dialect.MySQL5Dialect
        </property>
        <property name="show_sql">true</property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost/test
        </property>
        <property name="hibernate.connection.username">
            root
        </property>
        <property name="hibernate.connection.password">
            jiangyu
        </property>
        <mapping resource="Employee.hbm.xml" />
    </session-factory>
</hibernate-configuration> 

用 MySQL来储存数据:

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(20) DEFAULT NULL,
  `last_name` varchar(20) DEFAULT NULL,
  `salary` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

测试类:

package com.ydoing.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.ydoing.domain.Employee;

public class Main {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.configure();
        // ServiceRegistry serviceRegistry = new
        // ServiceRegistryBuilder().applySettings(conf.getProperties())
        // .buildServiceRegistry();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties())
                .build();
        SessionFactory factory = conf.buildSessionFactory(serviceRegistry);
        Session session = factory.openSession();
        Employee emp = new Employee();
        emp.setFirstName("Mac");
        emp.setLastName("Jack");
        emp.setSalary(100);
        Transaction tx = session.getTransaction();
        tx.begin();
        session.save(emp);
        tx.commit();
        session.close();
    }
}

控制台输出:

Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?) 

查看MySQL数据
这里写图片描述

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics