1.建立一个java项目,在目录下新建一个lib文件夹引入hibernate架包如图所示:
2. 新建com.LHB.domain包,在包中分别创建一个Employee.java和Employee.hbm.xml文件,
Employee.java中的代码如下:
package com.LHB.domain; import java.util.Date;
//该pojo/javabean/domain按照规范应当序列化,目的是可以唯一的表示该对象呢,同时可以在网络和文件传输
public class Employee implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String email;
private Date hiredate;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
} }
Employee.hbm.xml映射文件配置如下:
<?xml version="1.0" encoding="utf-8"?>
<!-- 映射文件通过DTD来指定格式 -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 该文件用于配置domain对象和表的映射关系 -->
<hibernate-mapping package="com.LHB.domain">
<class name="Employee" table="employee" >
<!-- id元素用于指定主键属性 -->
<!--
<id name="id" column="id" type="java.lang.Integer">
该元素用来指定主键生成的策略hilo native increment sequence uuid
<generator class="sequence">
<param name="sequence">emp_seq</param>
</generator>
</id>
-->
<!-- 在更改数据库时对主键生成策略做了修改 -->
<id name="id" column="id" type="java.lang.Integer">
<generator class="increment"></generator>
</id>
<!-- 如果id号希望用户自己设定,而不是由数据库MySQL -->
<!-- <id name="id" column="id" type="java.lang.Integer">
<generator class="assigned"/>
</id> -->
<!-- 对其它属性还要配置 -->
<property name="name" type="java.lang.String">
<column name="name" not-null="false" />
</property>
<property name="email" type="java.lang.String">
<column name="email" not-null="false" />
</property>
<property name="hiredate" type="java.util.Date">
<column name="hiredate" not-null="false" />
</property>
</class> </hibernate-mapping>
3.在项目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>
<!-- 配置使用的driver -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<!-- 配置dialect方言,明确告诉hibernate连接哪种数据库 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 显示出对应的sql语句 -->
<property name="show_sql">true</property>
<!-- 让hibernate给我们自动创建表 creat:如果mysql中没有该表则创建,如果有表则删除再创建
update:如果没有表则创建新表,如果有表则看表结构有没有变化,如果有变化则创建新表-->
<property name="hbm2ddl.auto">update</property>
<!-- 指定管理的对象映射文件 -->
<mapping resource="com/LHB/domain/Employee.hbm.xml"/> </session-factory>
</hibernate-configuration>
4. 创建一个测试类TestMain
package com.LHB.view; import java.util.Date; import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session; import com.LHB.domain.Employee;
import com.LHB.util.MySessionFactory; public class TestMain { public static void main(String[] args) {
// TODO Auto-generated method stub updateEmp();
//addEmployee();
}
/**
* 删除用户
*/
private static void delEmp() {
//删除
//获取一个session
Session session = MySessionFactory.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
try {
//修改1.先获取该雇员,然后删除
Employee employee=(Employee) session.load(Employee.class, new Integer(3));
session.delete(employee);
transaction.commit();
session.close(); }catch (Exception e) {
if(transaction!=null) {
transaction.rollback();
} throw new RuntimeException(e.getMessage());
} finally {
//关闭session
if(session!=null&&session.isOpen()) {
session.close();
} }
}
/**
* 更新用户
*/
private static void updateEmp() {
//修改用户
//获取一个会话
/*Session session = MySessionFactory.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction();
//修改用户1.获取要修改的用户,2.修改
//load是可以通过主键属性,获取该对象实例,《----》表的记录对应
Employee employee = (Employee)session.load(Employee.class, new Integer(3));
employee.setName("张三");
transaction.commit();
session.close();
*/
//添加事务回滚优化之后
Session session = MySessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
//do...
Employee employee = (Employee)session.load(Employee.class, new Integer(1));
//用户指定id号
//employee.setId(new Integer(100));
employee.setName("李四");
employee.setEmail("[email protected]"); /*//异常
int i=9/0;
//....
*/ transaction.commit(); }catch (Exception e) {
if(transaction!=null) {
transaction.rollback();
} throw new RuntimeException(e.getMessage());
} finally {
//关闭session
if(session!=null&&session.isOpen()) {
session.close();
} } }
/**
* 添加用户
*/
public static void addEmployee() {
//使用hibernate完成crud操作
//现在不使用service,直接测试
//1.创建Configuration,该对象用于读取hibernate.cfg.xml并完成初始化
Configuration configuration = new Configuration().configure();
//2.创建SessionFactory【这是一个会话工厂,是一个重量级的对象】
SessionFactory sessionFactory = configuration.buildSessionFactory();
//3.创建Session,相当于jdbc中的Connection
Session session = sessionFactory.openSession();
//4.对于hibernate,要求在进行增加,删除,修改的时候使用事物提交
Transaction transaction = session.beginTransaction(); try { //添加一个雇员
Employee employee = new Employee();
employee.setName("zhangsan");
employee.setEmail("[email protected]");
employee.setHiredate(new Date()); //保存,把对象保存到数据库
session.save(employee);//相当于insert into....[被hibernate封装]
transaction.commit();
session.close(); }catch (Exception e) {
if(transaction!=null) {
transaction.rollback();
} throw new RuntimeException(e.getMessage());
} finally {
//关闭session
if(session!=null&&session.isOpen()) {
session.close();
} }
} }