环境:
数据库:mariadb 10.2.16  https://downloads.mariadb.org/
配置好maven:见收藏的博文链接 https://www.cnblogs.com/ICE_Inspire/p/9250194.html

官方文档:http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#domain-model

具体过程:

1.新建一个maven project,如图

2.编辑pom.xml ,增加如下内容

 <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.3.2.Final</version>
</dependency>

hibernate-c3p0是为了解决:

WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)

之后,重新Reimport all maven project,如图

3.建立表 sql如下:

CREATE TABLE IF NOT EXISTS `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

项目里增加对应类:

public class Customer {
private Integer id; //主键id
private String name; //客户姓名
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
} //重写toString()方法
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + "]";
}
}

4.在src\main下建立文件夹resources,添加Customer.hbm.xml文件,内容如下:

<?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>
<!-- name代表的是实体类名(根据具体情况更改),table代表的是表名 -->
<class name="hibernate03.model.Customer" table="customer">
<!-- name=id代表的是customer类中属性 column=id代表的是table表中的字段 -->
<id name="id" column="id">
<!-- 主键生成策略 -->
<generator class="native"/>
</id>
<!-- 其他属性使用property标签来映射 -->
<property name="name" column="name" type="string"/>
</class>
</hibernate-mapping>

添加hibernate.cfg.xml文件,内容如下

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
" http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property> -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.c3p0.min_size">5</property> <!--在连接池中可用数据库连接的最小数目-->
<property name="hibernate.c3p0.max_size">30</property> <!--在连接池中所有数据库连接的最大数目-->
<property name="hibernate.c3p0.time_out">1800</property> <!--设定数据库连接的超时时间-->
<property name="hibernate.c3p0.max_statement">50</property> <!--可以被缓存的PreparedStatement的最大数目-->
<mapping resource="Customer.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

如果红色字体,请重新Reimport all maven project.

5.增加HibernateUtil工具类

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtil extends Object{
private static SessionFactory sessionFactory;
static
{
try{
Configuration configuration=new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
}catch (Throwable ex){
throw new ExceptionInInitializerError(ex);
}
}
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() throws HibernateException
{
Session session = threadLocal.get();
if (session == null){
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = threadLocal.get();
if (session != null)
session.close();
threadLocal.set(null);
} public static void shutdown(){
getSessionFactory().close();
} }

6.测试

public static void main( String[] args )
{
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
try{
Customer customer=new Customer();
customer.setId(3);
customer.setName("ICE_Inspire");
session.save(customer);
tx.commit();
System.out.println("保存成功!");
}catch(Exception e){
e.printStackTrace();
tx.rollback();
System.out.println("保存失败!");
}finally{
HibernateUtil.closeSession();
}
}

7.显示结果

七月 08, 2018 1:31:11 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.2.Final}
七月 08, 2018 1:31:11 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
七月 08, 2018 1:31:13 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
七月 08, 2018 1:31:13 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/test
七月 08, 2018 1:31:13 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001001: Connection properties: {user=root, password=****}
七月 08, 2018 1:31:13 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001003: Autocommit mode: false
七月 08, 2018 1:31:13 下午 com.mchange.v2.log.MLog
信息: MLog clients using java 1.4+ standard logging.
七月 08, 2018 1:31:13 下午 com.mchange.v2.c3p0.C3P0Registry
信息: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
七月 08, 2018 1:31:13 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001007: JDBC isolation level: <unknown>
七月 08, 2018 1:31:13 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@39db5c50 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@c4d328da [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, identityToken -> 1hge13a9wxed8vobdm3gs|42530531, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 30, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@1dcb54fb [ description -> null, driverClass -> null, factoryClassLocation -> null, forceUseNamedDriverClass -> false, identityToken -> 1hge13a9wxed8vobdm3gs|6676f6a0, jdbcUrl -> jdbc:mysql://localhost:3306/test, properties -> {user=******, password=******} ], preferredTestQuery -> null, privilegeSpawnedThreads -> false, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, extensions -> {}, factoryClassLocation -> null, identityToken -> 1hge13a9wxed8vobdm3gs|7d446ed1, numHelperThreads -> 3 ]
七月 08, 2018 1:31:14 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
七月 08, 2018 1:31:14 下午 org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
保存成功!

Process finished with exit code 0

备注:
如果提示*.hbm.xml not found,检查下target/classes/目录下是否有和main/resources/目录下一样的xml文件.

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>

IntelliJ IDEA使用hibernate的更多相关文章

  1. Intellij IDEA的Hibernate简单应用

    1.创建数据库及其表 create database demo;    use demo; CREATE TABLE `user` (   `id` int(10) unsigned NOT NULL ...

  2. *IntelliJ IDEA配置Hibernate

    为IntelliJ IDEA安装Hibernate插件

  3. 【笔记】IntelliJ IDEA配置Hibernate

    参考:imooc:http://www.imooc.com/video/7706 1.创建Hibernate的配置文件. 将依赖包导入项目.http://blog.csdn.net/a15337525 ...

  4. 【转载】Intellij IDEA的Hibernate简单应用

    转载自: https://www.cnblogs.com/yangyquin/p/5438248.html   1.创建数据库及其表 create database demo;    use demo ...

  5. *IntelliJ IDEA使用Hibernate连接数据库

    在IntelliJ IDEA中配置MySQL Database.

  6. intellij 编译 springmvc+hibernate+spring+maven 找不到hbm.xml映射文件

    1. 错误信息 Invocation of init method failed; nested exception is org.hibernate.MappingNotFoundException ...

  7. Intellij idea生成Hibernate实体类

    反向生成基于注解的Hibernate实体类 1. 为项目添加Hibernate支持 2. 在IDE右边找到database,然后按照步骤添加数据. 3. 保存后.在主面板左侧有persistence, ...

  8. 【转】IntelliJ IDEA下自动生成Hibernate映射文件以及实体类

    1.构建项目并添加项目结构配置以及配置初始参数 1.1.如图将基本的架子搭建好     1.2.点击File,弹出的菜单中点击Project Structure:     1.3.点击左侧的Modul ...

  9. spring入门(五) spring mvc+hibernate

    核心是让SessionFactory由Spring管理 1.引入依赖 <!-- https://mvnrepository.com/artifact/org.springframework/sp ...

随机推荐

  1. WAMP环境配置-Mysql安装

    1.下载并解压MySQL5.6.36压缩包(顺便重命名一下子). 2.将my-default.ini文件复制一份改名为my.ini,然后修改下面红框标注的地方 3.安装与启动服务. 以管理员的身份运行 ...

  2. c#学习基础(2)存储、值类型和引用类型、变量

    程序运行时,它的数据必须存储在内存中,数据项需要多大的内存.存储在什么地方以及如何存储都依赖该数据项的类型 运行中的程序使用两个区域来存储数据:栈和堆 栈是一个内存数组,是一个LIFO(last in ...

  3. kafka自定义序列化器

    <kafka权威指南> Customer.java public class Customer { private int customId; private String custome ...

  4. Spring课程 Spring入门篇 4-6 Spring bean装配之基于java的容器注解说明--@ImportResource和@Value java与properties文件交互

    1 解析 1.1 这两个注解应用在什么地方 1.2 应用方式 1.3 xml方式实现取值 2 代码演练 2.1 @ImportResource和@Value代码演练 1 解析 1.1 这两个注解应用在 ...

  5. JS中绑定事件顺序(事件冒泡与事件捕获区别)

    在JS中,绑定的事件默认的执行时间是在冒泡阶段执行,而非在捕获阶段(重要),这也是为什么当父类和子类都绑定了某个事件,会先调用子类绑定的事件,后调用父类的事件.直接看下面实例 <!Doctype ...

  6. JS基础学习——对象

    JS基础学习--对象 什么是对象 对象object是JS的一种基本数据类型,除此之外还包括的基本数据类型有string.number.boolean.null.undefined.与其他数据类型不同的 ...

  7. linux漏洞分析入门笔记-栈溢出

    ida7.0 ubuntu16.04 lts 0x00:环境配置 使用IDA远程调试Linux程序步骤如下: 1. 在进行远程调试之前需要对Linux平台进行一些准备工作.在IDA的安装目录中的dbg ...

  8. 【转】成型滤波与匹配滤波的MATLAB实现

    转载自:https://blog.csdn.net/yuan1164345228/article/details/45919315 Fd=1; Fs=8; Delay=3; R=0.5; [yf,tf ...

  9. Dynamics CRM RibbonWorkbench工具使用

    这边用的是RibbonWorkbench2016的工具,导入RibbonWorkbench2016解决方案即可.导入成功后在解决方案下面会多出一个快捷键小图标. 一.基本介绍 二.列表页获取选中记录的 ...

  10. Selenium2学习(十二)-- alert\confirm\prompt

    前言 不是所有的弹出框都叫alert,在使用alert方法前,先要识别出到底是不是alert.先认清楚alert长什么样子,下次碰到了,就可以用对应方法解决. alert\confirm\prompt ...