第一步:下载并导入需要用到的jar包,初始化Eclipse
下载到本地文件夹
初始化Eclipse,并将上述下载的jar文件全部导入
第二步:配置环境,完善hibernate.cfg.xml的编写
<hibernate-configuration>
<session-factory>
<property name ="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name ="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name ="hibernate.connection.url">jdbc:mysql://localhost:3306/hellohibernate?serverTimezone=Asia/Shanghai</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>
第三步:创建mysql数据库
登录数据库
创建hellohibernate数据库并初始化T_USER这个表
第四步:创建实体类并添加映射文件User.hbm.xml
User.Java:
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;
}
}
User.hbm.xml:
<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实现用户添加:
manageUser.java:
package cn.hrbust.dao;
import org.hibernate.cfg.Configuration;
import cn.hrbust.pojo.User;
import java.sql.Date;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.Session;
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("yjx");
u.setGender("female");
u.setAge(21);
u.setBirthday(Date.valueOf("2001-1-1"));
try {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
session = sf.openSession();
ts =session.beginTransaction();
session.save(u);
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (ts!=null){
ts.rollback();
}
}finally{
session.close();
sf.close();
}
}
}
第六步:运行Hibernate,添加用户,并在数据库中查看
运行成功:
查看数据库:
总结:通过跟随老师的详细讲解,熟练掌握了Hibernate的基础环境搭建,并且实现了添加用户功能的实现。