hibernate初始用(第一次作业
搭建hibernate使用环境
JavaSE-1.8, Mysql8.0, Esclipe2018
操作过程
1.首先创建一个普通的Java工程,并导入相关的JAR包.
2.导入已有的hibernate.cfg.xml文件并配置好.
<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?useSSL=false</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>
注释: 由于我本人电脑mysql版本是8.0版本,和连接mysql的jar包 版本相差很多,所以需要将useSSl设置成false.
3.新建pojo实体User类,存放用户基本信息.
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映射文件:
<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>
5.创建对应的数据库和数据库表:
6.最后创建manageUser.java类,去读取文件,创建事务
Configuration conf = new Configuration().configure();//1、读取配置文件
SessionFactory sf = conf.buildSessionFactory();// 2、创建SessionFactory
Session session = sf.openSession();// 3、打开Session
Transaction ts = null;
try{
ts = session.beginTransaction();// 4、开始一个事务
// 5、持久化操作
User user = new User();
user.setName("李嘉聪");
user.setGender("男");
user.setAge(21);
user.setBirthday(Date.valueOf("2021-5-7"));
session.save(user);
ts.commit();// 6、 提交事务
}catch(Exception e){
if (ts!=null){ ts.rollback();}
e.printStackTrace();
}finally{
session.close();// 7、关闭Session
}
}
}
运行截图
数据库界面: