首先先介绍一下使用Hibernate的7个步骤
1.创建Configuration对象,负责读取hibernate.cfg.xml
2.创建SessionFactory,负责ORM框架的持久化操作
3.创建Session
4.开始一个事务
5.持久化操作save/update/delete/get
6.提交事务
7.关闭Session
工程的准备
在elipse中新建一个Java程序
导包
添加hibernate的jar包
添加数据库驱动jar包
添加日志jar包
添加配置文件
在hibernate-release-5.2.10.Final\project\etc下找到log4j.properties将其拷贝到src下
在hibernate-release-5.2.10.Final\project\etc下找到hibernate.cfg.xml将其拷贝到src下
找到相关的配置信息
进行方言、连接数据库驱动、统一资源定位器、的配置
选择MySQL
创建数据库
测试URL是否正确
完成hibernate.cfg.xml中的配置
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hellohibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="show_sql">true</property>
<mapping resource="cn/hrbust/pojo/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
添加实体类和映射文件
src下创建User类
package cn.hrbust.pojo;
import java.sql.Date;
public class User {
private int id;
private String name;
private String gender;
int age;
Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
创建数据库T_USER表
<hibernate-mapping>
<class name="cn.hrbust.pojo.User" table="t_user">
<id name="id" column="id">
<generator class="native"/> <!-- 根据底层数据库自动选择 -->
</id>
<property name="name"/>
<property name="gender"/>
<property name="age"/>
<property name="birthday"/>
</class>
</hibernate-mapping>
package cn.hrbust.dao;
import java.sql.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.hrbust.pojo.User;
public class manageUser {
public static void main(String[] args) {
Configuration cfg = null;
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
//创建user
User u = new User();
u.setName("洪铭");
u.setGender("男");
u.setAge(21);
u.setBirthday(Date.valueOf("2000-1-1"));
try {
//创建Configuration对象
cfg = new Configuration().configure();
//创建Session工厂
sf = cfg.buildSessionFactory();
//创建Session
session = sf.openSession();
//创建事务
ts = session.beginTransaction();
//持久化操作:session保存对象
session.save(u);
//提交事务
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts != null) {
ts.rollback();
}
}finally {
//关闭session
session.close();
sf.close();
}
}
}
数据库查表
添加用户成功