实现ORM框架(hibernate)
搭建hibernate的使用环境
JavaSE-1.8, Mysql8.0, Esclipe2019
操作过程和运行截图
1.创建一个Java工程,导入相关的JAR包.
2.导入已有的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?useSSL=false</property>
<property name="hibernate.connection.username">roots</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>
3.创建mysql数据库用户表
4.新建实体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;
}
}
5.导入User.hbm.xml映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="false">
<class name="cn.hrbust.pojo.User" table="T_USER">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="age"/>
<property name="gender"/>
<property name="birthday"/>
</class>
</hibernate-mapping>
6.创建manageUser.java类,进行测试
package cn.hrbust.dao;
import java.sql.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.omg.CORBA.SystemException;
import cn.hrbust.pojo.User;
public class manageUser {
public static void main(String[] args) throws IllegalStateException, SystemException {
Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Transaction ts = null;
try{
ts = session.beginTransaction();
User user = new User();
user.setName("刘学凯");
user.setGender("男");
user.setAge(21);
user.setBirthday(Date.valueOf("2000-8-13"));
session.save(user);
ts.commit();
}catch(Exception e){
if (ts!=null){ ts.rollback();}
e.printStackTrace();
}finally{
session.close();
}
}
}
运行效果: