IDEA Maven构建Hibernate项目

17 篇文章 0 订阅
8 篇文章 0 订阅

IDEA Maven构建Hibernate项目

环境

java 12.0.1
Apache Maven 3.6.3
MySQL Server version: 5.7.18-20170830-log 20170531
hibernate-core-5.4.27.Final.jar
mysql-connector-java-8.0.21.jar
IntelliJ IDEA 2020.2.3 (Ultimate Edition)

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>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- Hibernate jar-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-agroal</artifactId>
            <version>5.4.27.Final</version>
            <type>pom</type>
        </dependency>
        <!-- MySQL JDBC -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <!-- log4j jar -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>12</source>
                    <target>12</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.hbm.xml</include>
                </includes>
            </resource>
        </resources>
    </build>


</project>

Hibernate配置文件

src/main/resources/hibernate.cfg.xml

数据库参数

  • [hostname] : 主机名(本地为localhost
  • [port] : 端口号(默认端口号为3306
  • [database] : 数据库名
  • [username] : 用户名
  • [password] : 密码

配置参数

  • hibernate.dialect : 数据库方言(映射数据库的SQL语法)
  • hibernate.connection.driver_class : JDBC
  • hibernate.connnection.url : 数据库主机地址(IP:端口号)
  • hibernate.connection.username : 数据库用户名
  • hibernate.connection.password : 数据库密码
  • hibernate.show_sql : 显示Hibernate进行映射操作时的SQL语句
  • hibernate.hbm2ddl.auto : Hibernate自动创建表的属性,update属性表明若数据库中已存在该表,则对表进行修改,否则新建表
  • mapping resource : 映射文件的路径

配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- dialect configuration -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

        <!-- database configuration -->
        <property name="hibernate.connection.url">jdbc:mysql://[hostname]:[port]/[database]</property>
        <property name="hibernate.connection.username">[username]</property>
        <property name="hibernate.connection.password">[password]</property>

        <!-- hibernate configuration-->
        <property name="hibernate.show_sql">true</property>

        <!-- update: create if table not exist, else update-->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- mapping resource -->
        <mapping resource="com/demo/hibernate/User.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

映射文件

参数

  • class
    • name : 包名和类名
    • table : 类映射到数据库的表名
    • catalog : 数据库名
    • id : PRIMARY KEY
      • name : 类中唯一标识一个对象的成员变量名
      • column : 类中成员变量映射到数据表的属性名
    • generator : AUTO_INCREMENT
      • class : AUTO_INCREMENT增长策略
    • property : 属性
      • name : 类中的成员变量名
      • column : 类中成员变量映射到数据表的属性名
      • length : 字段长度

映射文件

<?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 package="com.demo.hibernate">
    <class name="com.demo.hibernate.User" table="user" catalog="web">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="user" column="user" length="128"></property>
        <property name="password" column="password" length="128"></property>
    </class>
</hibernate-mapping>

Java代码

User类

src/main/java/com/demo/hibernate/User.java

package com.demo.hibernate;

public class User {
    private int id;
    private String user;
    private String password;

    public User(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public User() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
};

Hibernate类

src/main/java/com/demo/hibernate/Hibernate.java

package com.demo.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

import java.util.ArrayList;
import java.util.List;

public class Hibernate {
    private Configuration configuration;
    private StandardServiceRegistry standardServiceRegistry;
    private SessionFactory sessionFactory;
    protected Session session;
    protected Transaction transaction;

    public Hibernate() {
        try {
            configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
            sessionFactory = configuration.buildSessionFactory(standardServiceRegistry);
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertUser(List<User> userList) {
        for (User user : userList) {
            session.save(user);
        }
        transaction.commit();
    }

    public static void main(String[] args) {
        Hibernate hibernate = new Hibernate();
        List<User> userList = new ArrayList<User>();
        userList.add(new User("Tony", "123456"));
        userList.add(new User("Tom", "123456"));
        userList.add(new User("Tim", "123456"));
        userList.add(new User("Charles", "123456"));
        userList.add(new User("Bill", "123456"));

        hibernate.insertUser(userList);
    }
}

Hibernate核心类

Configuration

加载Hibernate核心配置文件hibernate.cfg.xml

SessionFactory

SessionFactory是应用程序域模型到数据库映射的线程安全(且不可变)的表示,根据Hibernate核心配置文件连接数据库并实现类到数据表的映射。

创建SessionFactory对象的代价高昂,因此,对于任何给定的数据库,应用程序都应该只有一个关联的SessionFactory

SessionFactory维护Hibernate在所有会话中使用的服务,如二级缓存、连接池、事务系统集成等。

A thread-safe (and immutable) representation of the mapping of the application domain model to a database. Acts as a factory for org.hibernate.Session instances. The EntityManagerFactory is the JPA equivalent of a SessionFactory and basically, those two converge into the same SessionFactory implementation.

A SessionFactory is very expensive to create, so, for any given database, the application should have only one associated SessionFactory. The SessionFactory maintains services that Hibernate uses across all Session(s) such as second level caches, connection pools, transaction system integrations, etc.

Session

Session对象是单线程、短期的对象Session封装了JDBC(java.sql.Connection)对象并作为Transcation对象的工厂,调用Session对象来进行增删改查操作(save(), delete(), update(), get()),它通常维护应用程序域模型的“可重复读取”持久性上下文(一级缓存)。

A single-threaded, short-lived object conceptually modeling a “Unit of Work” (PoEAA). In JPA nomenclature, the Session is represented by an EntityManager.

Behind the scenes, the Hibernate Session wraps a JDBC java.sql.Connection and acts as a factory for org.hibernate.Transaction instances. It maintains a generally “repeatable read” persistence context (first level cache) of the application domain model.

Transcation

Transcation对象是应用程序用来划分单个物理事务边界的单线程、短期对象,实现数据库事务的提交和回滚(commit(), rollback())。

A single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries. EntityTransaction is the JPA equivalent and both act as an abstraction API to isolate the application from the underlying transaction system in use (JDBC or JTA).

测试结果

select * from user;

参考

Hibernate ORM 5.4.27.Final User Guide

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值