Hibernate 初始配置

创建数据库

DROP DATABASE if exists hibernate;
create database hibernate charset=utf8mb4;
use hibernate;
create table user(
    id int auto_increment primary key,
    name varchar(10),
    gender varchar(10),
    age int,
    birthday date
)

Maven 导入

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>hibernate</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.31.Final</version>
        </dependency>
    </dependencies>
</project>

创建实体类

在这里插入图片描述

package cn.edu.hrbust.entity;

import java.sql.Date;
import java.util.Objects;

/**
 * @ClassName UserEntity
 * @Description
 * @Author Shen
 * @Date 2021/5/10 22:28
 * @Version 1.0
 **/
public class User {
    private int id;
    private String name;
    private String gender;
    private Integer age;
    private 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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User that = (User) o;
        return id == that.id && Objects.equals(name, that.name) && Objects.equals(gender, that.gender) && Objects.equals(age, that.age) && Objects.equals(birthday, that.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, gender, age, birthday);
    }
}

创建主配置文件

注意数据库配置

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=Asia/Shanghai&amp;characterEncoding=utf8</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">zs2201</property>
        <mapping resource="User.hbm.xml"/>
        <!-- DB schema will be updated if needed -->
        <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

创建映射文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="cn.edu.hrbust.entity.User" table="user" schema="hibernate">
        <id name="id">
            <column name="id" sql-type="int(11)"/>
        </id>
        <property name="name">
            <column name="name" sql-type="varchar(10)" length="10" not-null="true"/>
        </property>
        <property name="gender">
            <column name="gender" sql-type="varchar(10)" length="10" not-null="true"/>
        </property>
        <property name="age">
            <column name="age" sql-type="int(11)" not-null="true"/>
        </property>
        <property name="birthday">
            <column name="birthday" sql-type="date" not-null="true"/>
        </property>
    </class>
</hibernate-mapping>

测试类

import cn.edu.hrbust.entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.sql.Date;

public class Main {
    public static void main(final String[] args) {
        User u = new User();
        u.setName("张三");
        u.setGender("男");
        u.setAge(21);
        u.setBirthday(Date.valueOf("2001-1-1"));
        Configuration cfg = null;
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        try {
            cfg = new Configuration().configure();
            sf = cfg.buildSessionFactory();
            session = sf.openSession();
            ts = session.beginTransaction();
            session.save(u);
            ts.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
            if (ts != null) {
                ts.rollback();
            }
        } finally {
            session.close();
            sf.close();
        }
    }
}

测试结果

在这里插入图片描述

期间遇到的问题

保存'张三'时数据库乱码,解决: 数据库URL添加characterEncoding=utf8参数,注意XML中 & 转义为&amp;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值