Idea 创建web+nibernate工程
Idea 创建web+nibernate工程
数据库
- 创建数据库nibernate_day01
- 创建表
CREATE TABLE `cst_customer` ( `cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)', `cust_name` VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)', `cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源', `cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '客户所属行业', `cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客户级别', `cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定电话', `cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '移动电话', PRIMARY KEY (`cust_id`) ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; |
Hibernate资料
- 下载地址
https://sourceforge.net/projects/hibernate/files/hibernate-orm/
- 目录结构
- Documentataion: 所有文档
- Lib 所有需要的jar包
- Project 所有案例
- 所需要的jar包
- D:\hibernate-release-5.4.10.Final\lib\required\*.jar
- 数据库驱动包
- 日志记录的包
IDEA创建工程
- 创建新project(此处以创建web项目为例)
勾选Web Application + Hibernate
同时勾选 ”Create default hibernate configuration and main class”
这样创建的工程中就自动带有hibernate.cfg.xml文件
- 工程配置 ProjectStructure
- Modules-Sources
在web目录下新建一个目录,名为 WEB-INF,在WEB-INF目录下新建两个目录,名为 classes 和 lib。
classes:.class文件存放位置
lib: 整个项目所用到的JAR文件存放位置
-
- Modules - Paths
勾选 Use module compile output path,并将 Output path 和 Test output path 改为刚才web目录下新建的 classes 文件夹
目的:在构建项目时,能将.class文件输出至 classes 文件夹中
在下面的JavaDoc中添加web目录下的 lib文件夹
-
- Modules – Dependencies
添加web目录下的lib文件夹以及Tomcat的Library
在添加 lib文件夹时选择 Jar Directory
-
- Libraries
添加web目录下的lib文件夹,选择 Jar Directory
-
- Facets
在Deployment Descriptor中添加 web.xml 文件
-
- Artifacts
勾选 Include in project build 和 Show content of elements 两个选项,点击OK
- 配置tomcat
Edit Configurations - Tomcat Server - Local
这是配置Tomcat的过程
添加jar包
连接数据
根据数据库表自动生成实体类 和 映射文件(*.hbm.xml)
完善hibernate.cfg.xml文件
测试
package com.fiberhome.hibernate.test; import com.fiberhome.hibernate.domain.CstCustomer; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; /** * Created by Administrator on 2020/1/8. */ public class hibernateTest { @Test public void demo1(){ // 加载Hibernate的核心配置文件. Configuration configuration = new Configuration().configure(); // 创建一个SessionFactory的对象. SessionFactory sessionFactory = configuration.buildSessionFactory(); // 创建Session(相当于JDBC中的Connection) Session session = sessionFactory.openSession(); // 开启事务: Transaction transaction = session.beginTransaction(); // 完成操作: CstCustomer customer = new CstCustomer(); customer.setCustName("柳岩"); session.save(customer); // 提交事务 transaction.commit(); // 释放资源 session.close(); } }
|