使用Hibernate实现单表CRUD,数据库使用MySQL
建立customer表
create database test;
create table customer (
id int primary key auto_increment,
name varchar(20),
age int,
city varchar(20)
);
创建JavaBean对象
package rock.lee.bean;
import java.io.Serializable;
public class Customer implements Serializable{
private static final long serialVersionUID = -3229680950625733244L;
private Integer id;
private String name;
private Integer age;
private String city;
public Customer() {
super();
}
public Customer(String name, Integer age, String city) {
super();
this.name = name;
this.age = age;
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", age=" + age+ ", city=" + city + "]";
}
}
Hibernate是一个Object Relational Mapping框架,这里采用配置文件的形式实现JavaBean对象映射到关系型数据表
编写hbm.xml文件,在JavaBean所在的包下建立Customer.hbm.xml文件,引入hibernate3.jar中org/hibernate/hibernate-mapping-3.0.dtd里的DTD约束
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- name:Bean的完整的类名 table:与Bean所要映射的数据库表名 catalog: 数据库库名 --> <class name="rock.lee.bean.Customer" table="customer" catalog="test"> <!-- id:标签用于配置主键 name: Customer类中的主键属性 column:数据库中所对应的列名 type:属性的类型 --> <id name="id" column="id" type="int"> <!-- generator标签用于配置主键的生成策略 --> <generator class="native"></generator> </id> <!-- property标签用于配置其它Bean属性所对应的表列明 --> <property name="name" column="name" type="java.lang.String"></property> <property name="age" column="age" type="int"></property> <property name="city" column="city" type="java.lang.String"></property> </class> </hibernate-mapping>
<proterty>标签中type的取值
编写Hibernate核心配置文件hibernate.cfg.xml, 引入hibernate3.jar 中/org/hibernate/hibernate-configuration-3.0.dtd 的配置文件约束
<!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.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 配置数据库方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 向控制台打印SQL语句 --> <property name="show_sql">true</property> <!-- SQL语句格式化打印 --> <property name="hibernate.format_sql">true</property> <!-- 可以自动根据类生成DDL 建表语言,完成自动建表 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 加载 hbm 映射文件 --> <mapping resource="rock/lee/bean/Customer.hbm.xml" /> </session-factory> </hibernate-configuration>
com.mysql.jdbc.Driverjdbc:mysql:///testrootrootorg.hibernate.dialect.MySQLDialecttruetrueupdate
编写测试用例
CRUD的代码结构
@Test
public void test(){
Configuration configuration = new Configuration().configure();// 实例化配置对象,加载配置文件 hibernate.cfg.xml
SessionFactory sessionFactory = configuration.buildSessionFactory();// 创建Session连接工厂
Session session = sessionFactory.openSession();//创建Session
Transaction transaction = session.beginTransaction();//开启事物
//.....编写CRUD代码
transaction.commit();//提交事务
session.close();//关闭session
sessionFactory.close();//关闭session工厂
}
这段代码的流程
保存:
@Test
public void testSave(){
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Customer c = new Customer("小明",18,"北京");
session.save(c);
transaction.commit();
session.close();
sessionFactory.close();
}
通过ID获取数据:
@Test
public void testSave(){
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Customer c = new Customer("小明",18,"北京");
session.save(c);
transaction.commit();
session.close();
sessionFactory.close();
}
更新数据:
@Test
public void testUpdate(){
Configuration configuration = new Configuration().configure();// 实例化配置对象,加载配置文件 hibernate.cfg.xml
SessionFactory sessionFactory = configuration.buildSessionFactory();// 创建Session连接工厂
Session session = sessionFactory.openSession();//创建Session
Transaction transaction = session.beginTransaction();//开启事物
Customer customer = new Customer();
customer.setId(1);
customer.setName("小丽");
customer.setAge(25);
customer.setCity("上海");
session.update(customer);
transaction.commit();//提交事务
session.close();//关闭session
sessionFactory.close();//关闭session工厂
}
HQL查询所有数据:
@Test
public void testFindAllByHQL(){
Configuration configuration = new Configuration().configure();// 实例化配置对象,加载配置文件 hibernate.cfg.xml
SessionFactory sessionFactory = configuration.buildSessionFactory();// 创建Session连接工厂
Session session = sessionFactory.openSession();//创建Session
Transaction transaction = session.beginTransaction();//开启事物
String hql = " from Customer";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List <Customer>list = query.list();
System.out.println(list);
transaction.commit();//提交事务
session.close();//关闭session
sessionFactory.close();//关闭session工厂
}
SQL查询所有数据:
@Test
public void testFindALllBySQL(){
Configuration configuration = new Configuration().configure();// 实例化配置对象,加载配置文件 hibernate.cfg.xml
SessionFactory sessionFactory = configuration.buildSessionFactory();// 创建Session连接工厂
Session session = sessionFactory.openSession();//创建Session
Transaction transaction = session.beginTransaction();//开启事物
String sql = "select * from customer";
SQLQuery query = session.createSQLQuery(sql);
@SuppressWarnings("unchecked")
List<Object[]> list = query.list();
for (Object[] objs : list) {
System.out.println(Arrays.toString(objs));
}
transaction.commit();//提交事务
session.close();//关闭session
sessionFactory.close();//关闭session工厂
}
通过ID删除数据:
@Test
public void testDelete(){
Configuration configuration = new Configuration().configure();// 实例化配置对象,加载配置文件 hibernate.cfg.xml
SessionFactory sessionFactory = configuration.buildSessionFactory();// 创建Session连接工厂
Session session = sessionFactory.openSession();//创建Session
Transaction transaction = session.beginTransaction();//开启事物
Customer customer = new Customer();
customer.setId(1);
session.delete(customer);
transaction.commit();//提交事务
session.close();//关闭session
sessionFactory.close();//关闭session工厂
}
通过操作Customer对象,实现了对数据表的CRUD操作,其中最为核心的一个Hibernate接口是Session接口,所有的CRUD操作都是通过Session接口完成的。
测试用例中的一些代码并不合理,只是为了说明Hibernate单表CRUD中所使用到的API。