本文共 3188 字,大约阅读时间需要 10 分钟。
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目录下:
This class contains the employee detail.
还需要告诉Hibernate数据库的信息,用hibernate.cfg.xml描述,放在src目录下::
org.hibernate.dialect.MySQL5Dialect true com.mysql.jdbc.Driver jdbc:mysql://localhost/test root jiangyu
用 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数据