实现ORM框架的入门实例(hibernate)
搭建hibernate的使用环境
JavaSE-1.8, Mysql8.0, Esclipe2019
操作过程和运行截图
1.创建一个普通的Java工程,导入相关的JAR包.
2.导入已有的hibernate.cfg.xml文件
<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">root</property>
<property name="hibernate.connection.password">123456789</property>
<property name="show_sql">true</property>
<mapping resource="cn/hrbust/pojo/User.hbm.xml"/>
</session-factory>
3.新建实体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;
}
}
4.导入User.hbm.xml映射文件:
<!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>
5.创建mysql数据库用户表
6.创建manageUser.java类,进行测试
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("2021-5-7"));
session.save(user);
ts.commit();
}catch(Exception e){
if (ts!=null){ ts.rollback();}
e.printStackTrace();
}finally{
session.close();
}
}
}
运行效果:
插入数据如下:
配置途中eclipse出现数据库链接失败的问题,经检查发现是mysql8.0版本过高,需要指明是否进行SSL连接,在配置hibernate.connection.url处添加“useSSL=false”即可。