包结构如下图所示(按图标进行对齐):

环境搭好后代码分为以下几步:

 /**
* private static final Configuration CONFIGURATION;
* private static final SessionFactory SESSION_FACTORY;
* 1、加载配置文件
* Configuration CONFIGURATION = new Configuration().configure();
* 2、创建 session工厂
* SessionFactory SESSION_FACTORY = CONFIGURATION.buildSessionFactory();
* 3、创建session (类似于connection)
* Session SESSION_FACTORY.getCurrentSession()
* 4、开启事务
* Transaction tx = session.beginTransaction();
* 5、操作
* 6、提交事务
* tx.commit();(如果 session 不是线程绑定需执行session.close();)
* @author Administrator
*
*/

下面进行详细说明:

创建customer   javabean

 package cn.itcast.domain;

 public class Customer {
private long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_phone;
private String cust_mobile;
public long getCust_id() {
return cust_id;
}
public void setCust_id(long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
public String getCust_mobile() {
return cust_mobile;
}
public void setCust_mobile(String cust_mobile) {
this.cust_mobile = cust_mobile;
} }

在javaBean所在的包下创建映射关系文件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表名 catalog 数据库名(可省略) -->
<class name="cn.itcast.domain.Customer" table="customer" catalog="hibernate">
<!-- id 表示主键 name类属性名 column表中字段名 如果相同可以省略-->
<id name="cust_id" column="cust_id"><generator class="native"/></id>
<!-- property 表示表中的普通属性 -->
<property name="cust_name" column="cust_name"/>
<property name="cust_source" column="cust_source"/>
<property name="cust_industry" column="cust_industry"/>
<property name="cust_level" column="cust_level"/>
<property name="cust_phone" column="cust_phone"/>
<property name="cust_mobile" column="cust_moblie"/>
<!-- length 字段长度 type 数据类型-->
</class>
</hibernate-mapping>

在src下创建Hibernate的配置文件    hibernate.cfg.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 必要的配置信息 :连接数据库的基本参数 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/Hibernate?characterEncoding=utf8</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否输出sql语句 -->
<property name="show_sql">true</property>
<!-- 是否格式化sql语句 -->
<property name="format_sql">true</property>
<!-- Hibernat的hbm2ddl(数据定义语言:cteate drop alter ...)-->
<!--
hbm2ddl.auto的取值:
*none :不用Hibernate自动生成表
*create : 每次都会创建一个新的表(测试)
*create-drop:每次都会创建一个表,执行程序结束后删除这个表(测试)
*update :如果数据库中有表使用原来的表,创建一个新表,可以更新表结构
*validate :只会使用原来的表对映射关系进行校验
-->
<property name="hbm2ddl.auto">update</property>
<!-- 配置本地jdbc事务配置 ,通过getCurrentSession创建的session会绑定当前线程
thread 对象生命周期会与本地线程绑定
jta 对象生命周期与JTA事务绑定
managed Hibernate委托程序管理对象的生命周期
-->
<property name="current_session_context_class">thread</property> <!-- hibernate内部维护有一个连接池,如果要使用c3p0 等外部连接池 可以添加相应的jar包后进行配置 -->
<!-- 最小连接数 -->
<property name="c3p0.min_size">5</property>
<!-- 最大连接数 -->
<property name="c3p0.max_size">20</property>
<!-- 设定数据库连接的过期时间 以秒为单位 -->
<property name="c3p0.timeout">120</property>
<!-- 没3000秒检查所有数据库的空闲连接 以秒为单位-->
<property name="c3p0.idle_test_period">3000</property> <!-- 加载映射 -->
<property name="myeclipse.connection.profile"></property>
<mapping resource="cn/itcast/domain/Customer.hbm.xml" />
</session-factory>
</hibernate-configuration>

封装加载配置类为工具类:

 package cn.util;

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 加载配置文件 封装工具类
* @author Administrator
*
*/
public class HibernateUtil {
private static final Configuration CONFIGURATION;
private static final SessionFactory SESSION_FACTORY;
static{
//加载配置文件
CONFIGURATION = new Configuration().configure();
//创建一个SessionFactory
SESSION_FACTORY = CONFIGURATION.buildSessionFactory();
}
/**
* 提供获得Session的方法
*/
/**
* 直接创建新的Session实例 使用完成后需要调用 close方法手动关闭
* @return
*/
public static Session openSession() {
return SESSION_FACTORY.openSession();
}
/**
* 创建的session会被绑定到当前线程中,它在提交或回滚操作时会自动关闭
* @return
*/
public static Session getCurrentSession(){ return SESSION_FACTORY.getCurrentSession();
}
}

创建测试类进行测试:

 public class Demo1 {

 public static void main(String[] args) {
////获取session
//Session session = HibernateUtil.getCurrentSession();
////开启事务
//Transaction tx = session.beginTransaction();
//Customer customer= new Customer();
//customer.setCust_name("小王");
//customer.setCust_source("网络推广");
//session.save(customer);
////事务提交
//tx.commit();
////如果采用 openSession 获取实例 还需要 执行session.close();释放资源
////session 为轻量级 Configuration SessionFactory为重量级 之间重建所消耗的资源不同 //Session session = HibernateUtil.getCurrentSession();
//Transaction tx = session.beginTransaction();
//Customer customer = session.get(Customer.class,Long.valueOf("1"));
//session.delete(customer);
//tx.commit(); Session session =HibernateUtil.getCurrentSession();
Transaction tx = session.beginTransaction();
Customer customer = session.get(Customer.class,Long.valueOf("2"));
customer.setCust_mobile("124575615121");
session.update(customer);
tx.commit();
}
}

Hibernate连接数据库的更多相关文章

  1. JDBC、mybatis、hibernate连接数据库

    JDBC连接数据库五步骤: 一.加载驱动 Class.forName(“com.mysql.jdbc.Driver”); 二.建立连接 Connection conn = DriverManager. ...

  2. MySQL数据库的使用流程,代码解释+Hibernate连接数据库

    数据库的使用流程: 1.注册驱动: 2.用DriverManager.getConnection方法获得连接对象con: A方法:  3.用连接对象的createStatement()方法,获得可以执 ...

  3. hibernate连接数据库和反向工程

    一.JSP界面连接数据库: 导包:将11个包倒进web-inf的lib目录下: 二.建立hibernate.cfg.xml的配置文件:!注意:是放到项目SRC目录下: 三.将视图切换到java下,在左 ...

  4. hibernate连接数据库和使用

    hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibe ...

  5. Hibernate连接数据库超时设置autoReconnect=true

    如果连接闲置8小时 (8小时内没有进行数据库操作), mysql就会自动断开连接, 要重启tomcat. 不用hibernate的话, connection url加参数: autoReconnect ...

  6. hibernate连接数据库的步骤

    三个准备 一.导包   mysql二.在默认src下创建hibernate.cfg.xml   1.创建xml文件,命名为hibernate.cfg.xml 2.添加约束   (在org.hibern ...

  7. hibernate 连接数据库时报错

         错误信息 : com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allo ...

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

    在IntelliJ IDEA中配置MySQL Database.

  9. hibernate连接数据库中文乱码

    4.做完这两步还是不行,需要修改hibernate的配置文件hibernate.cfg.xml,在配置文件配置hibernate.connection.url属性.示例: <property n ...

随机推荐

  1. Java随机数使用

    JAVA取随机数的三种方式: Math.random() System.currentTimeMillis() random.nextInt() 废话不多说,看代码: /** *取单个随机数 *Mat ...

  2. jquery腾讯换肤的一些技术实现

    //检查cookie if($.cookie("skinID")){ $("#cssSkin").attr("href","/st ...

  3. Mysql 字符函数详解

    MySql 所有字符串函数函数详解 ASCII(str) 返回str最左边第一位字符的ASCII编码,如果str为空,则返回 0 .如果str为NULL,则返回NULL -- 只返回a的ASCII编码 ...

  4. python装饰器、迭代器、生成器

    装饰器:为已存在的函数或者或者对象添加额外的功能 def wrapper(f): #装饰器函数,f是被装饰的函数 def inner(*args,**kwargs): '''在被装饰函数之前要做的事' ...

  5. 处理半连接SQL自动改写内连接SQL一例

    昨天刚写了半连接改写系列,今天就遇到了此类型SQL: 优化前 耗时:28s 返回:0 SELECT D.DAILYAUDITNO, D.TRANSTOACC FROM PB_DOIC.MM_DAILY ...

  6. js 技巧 (七)JS代码判断集锦(之一)

    JS代码判断集锦(之一) ~~~~~~~~~~~~~~~~~~ <script language="JavaScript"> function checkid(iden ...

  7. Python之使用eval()函数将字符串的数据结构提取出来

    data = input('请输入你要修改的对象:').strip() ''' 输入下面的字典列表 [{'backend':'www.oldboy1.org','record':{'server':' ...

  8. FPGA学习笔记(六)—— 时序逻辑电路设计

    用always@(posedge clk)描述        时序逻辑电路的基础——计数器(在每个时钟的上升沿递增1) 例1.四位计数器(同步使能.异步复位) // Module Name: coun ...

  9. 【03】emmet系列之CSS语法

    [01]emmet系列之基础介绍 [02]emmet系列之HTML语法 [03]emmet系列之CSS语法 [04]emmet系列之编辑器 [05]emmet系列之各种缩写   单位: 有几个常用值别 ...

  10. 用C# ASP.net将数据库中的数据表导出到Excel中

    需要用到组件GridView和一个button即可. 给GridView添加一个数据源, 选择你想要的数据库中的表的字段,添加成功后GridView中就显示数据. 再添加一个button,双击控件添加 ...