最近研发的项目需要使用Hibernate,很久没有使用Hibernate了,做了一个简单的CRUD作为示例,比较简单,直接上代码吧,
首先创建数据库和表
CREATE DATABASE mybusiness;
USE mybusiness;
CREATE TABLE customers(
C_ID int NOT NULL AUTO_INCREMENT,
name varchar(20),
address varchar(20),
PRIMARY KEY(C_ID)
);
创建Hibernate配置文件
<?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 name="">
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/mybusiness</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.show_sql">true</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="customers.hbm.xml" />
</session-factory>
</hibernate-configuration>
创建ORM文件
<?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="Customer" table="customers">
<id column="C_ID" name="customerID" type="int">
<generator class="native">
</generator>
</id>
<property name="customerName">
<column name="name">
</column>
</property>
<property name="customerAddress">
<column name="address">
</column>
</property>
</class>
</hibernate-mapping>
创建模型类
public class Customer {
private int customerID;
private String customerName;
private String customerAddress;
public Customer() {
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
最后创建测试类
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class CRUDTest {
public static void main(String[] args) {
deleteTest();
// readTest();
}
/*
* 增加一个客户资料
*/
public static void createTest() {
Session session = null;
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
session.beginTransaction();
System.out.println("Adding a customer record !");
Customer customer = new Customer();
customer.setCustomerName("Customer-a");
customer.setCustomerAddress("Address1");
session.save(customer);
session.getTransaction().commit();
System.out.println("Done!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
session.flush();
session.close();
}
}
/*
* 读取customers表
*/
public static void readTest() {
Session session = null;
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
session.beginTransaction();
System.out.println(org.hibernate.Version.getVersionString());
String HQL_QUERY = "from Customer customers";
org.hibernate.Query query = session.createQuery(HQL_QUERY);
List list = query.list();
System.out.println("Recieving " + list.size() + " Records:");
for (Iterator it = list.iterator(); it.hasNext();) {
Customer customer = (Customer) it.next();
System.out.println("Name:" + customer.getCustomerName());
System.out.println("Address:" + customer.getCustomerAddress());
System.out.println("ID:" + customer.getCustomerID());
System.out.println("----------");
}
session.getTransaction().commit();
System.out.println("Done!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
session.flush();
session.close();
}
}
/*
* 更新一条记录
*/
public static void updateTest() {
Session session = null;
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
session.beginTransaction();
String HQL_QUERY = "from Customer customers where customers.customerID = :customerId";
org.hibernate.Query query = session.createQuery(HQL_QUERY);
// Prepared statement
query.setParameter("customerId", 1);
for (Iterator it = query.iterate(); it.hasNext();) {
Customer customer = (Customer) it.next();
customer.setCustomerName("Customer1");
}
session.getTransaction().commit();
System.out.println("Done!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
session.flush();
session.close();
}
}
/*
* 删除一条记录
*/
public static void deleteTest() {
Session session = null;
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
session.beginTransaction();
Customer cust = new Customer();
cust.setCustomerID(1);
session.delete(cust);
session.getTransaction().commit();
System.out.println("Done!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
session.flush();
session.close();
}
}
}
经过测试通过