使用Hibernate的“3个准备,7个步骤”
准备1:导入Hibernate库(jar包)
下载网站: http://sourceforge.net/projects/hibernate/files/
准备2:添加配置文件 -- hibernate.cfg.xml (放在src下)
创建数据库
<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/hibernateTest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"> </property>
<property name="show_sql">true</property>
<mapping resource="cn/hrbust/pojo/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
准备3:添加实体类和映射文件(User.hbm.xml),通常放在一个目录下。
创建实体类,创建映射文件,创建表
创建实体类:实体类与数据库表的字段对应,设置id与数据库主键对应。
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;
}
}
创建表:
创建映射文件:映射文件要与实体类在同一个package里,且文件名与实体类名相同。
<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>
使用Hibernate实现用户添加
7个步骤:
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) {
// TODO Auto-generated method stub
Configuration cfg=null;
SessionFactory sf=null;
Session session =null;
Transaction ts=null;
User u=new User();
u.setName("闫女士");
u.setGender("女");
u.setAge(22);
u.setBirthday(Date.valueOf("1999-11-28"));
try {
//1.创建Configuration对象 配置文件
cfg=new Configuration().configure();
//2.创建SessionFactory
sf=cfg.buildSessionFactory();
//3.创建一个session
session =sf.openSession();
//4.开始一个事务
ts=session.beginTransaction();
//5.持久化操作 save/update/delete/get
session.save(u);
//6.提交事务
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts!=null) {
ts.rollback();
}
}finally {
//7.关闭Session
session.close();
sf.close();
}
}
}
添加完成:
数据库表:
报错,遇到日志输出问题,修改配置文件。
总结:跟着老师的视频进行配置操作,整体下来还是比较顺利的。大致了解了orm框架,简化了开发人员对数据库表的操作。