Hibernate连接数据库
包结构如下图所示(按图标进行对齐):

环境搭好后代码分为以下几步:
/**
* 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连接数据库的更多相关文章
- JDBC、mybatis、hibernate连接数据库
JDBC连接数据库五步骤: 一.加载驱动 Class.forName(“com.mysql.jdbc.Driver”); 二.建立连接 Connection conn = DriverManager. ...
- MySQL数据库的使用流程,代码解释+Hibernate连接数据库
数据库的使用流程: 1.注册驱动: 2.用DriverManager.getConnection方法获得连接对象con: A方法: 3.用连接对象的createStatement()方法,获得可以执 ...
- hibernate连接数据库和反向工程
一.JSP界面连接数据库: 导包:将11个包倒进web-inf的lib目录下: 二.建立hibernate.cfg.xml的配置文件:!注意:是放到项目SRC目录下: 三.将视图切换到java下,在左 ...
- hibernate连接数据库和使用
hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibe ...
- Hibernate连接数据库超时设置autoReconnect=true
如果连接闲置8小时 (8小时内没有进行数据库操作), mysql就会自动断开连接, 要重启tomcat. 不用hibernate的话, connection url加参数: autoReconnect ...
- hibernate连接数据库的步骤
三个准备 一.导包 mysql二.在默认src下创建hibernate.cfg.xml 1.创建xml文件,命名为hibernate.cfg.xml 2.添加约束 (在org.hibern ...
- hibernate 连接数据库时报错
错误信息 : com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allo ...
- *IntelliJ IDEA使用Hibernate连接数据库
在IntelliJ IDEA中配置MySQL Database.
- hibernate连接数据库中文乱码
4.做完这两步还是不行,需要修改hibernate的配置文件hibernate.cfg.xml,在配置文件配置hibernate.connection.url属性.示例: <property n ...
随机推荐
- 笔试算法题(07):还原后序遍历数组 & 半翻转英文句段
出题:输入一个整数数组,判断该数组是否符合一个二元查找树的后序遍历(给定整数数组,判定其是否满足某二元查找树的后序遍历): 分析:利用后序遍历对应到二元查找树的性质(序列最后一个元素必定是根节点,从左 ...
- HDFS的Java API 对文件的操作
在本次操作中所用到的命令 1.首先启动HDFS $HADOOP_HOME/sbin/start-dfs.sh 2.关防火墙 切换到root用户,执行service iptables stop 3.拷贝 ...
- awk,grep,sed文本格式化处理
一.awk取列 [root@web01 ~]# cat /etc/passwd|awk -F ':' '{print $1"\t\t"$7}' ###-F指定分隔符 root /b ...
- 树莓派 -- bcm2835 library (1)
bcm2835 library提供了user space 操作IO的代码. 本文不涉及代码分析,先直观的按照user guide完成操作. 1. 在Raspberry中安装bcm2835 librar ...
- uva 10596 - Morning Walk
Problem H Morning Walk Time Limit 3 Seconds Kamal is a Motashota guy. He has got a new job in Chitta ...
- MySQL-Transfer2.2发布
http://dinglin.iteye.com/blog/1888640 Transfer 2.2发布.下载地址 版本说明 1. 基于版本 Percona-5.5.31 ,简单用法是先安装好官方或 ...
- [codevs4655] 序列终结者(Splay)
传送门 支持操作: 1.区间加 2.区间翻转 3.区间求最大值 splay模板 注意:update 里更新 max 时需要取 3 个值的 Max 别忘了各种边界讨论 ——代码 #include < ...
- 仪仗队(bzoj 2190)
Description 作为体育委员,C君负责这次运动会仪仗队的训练.仪仗队是由学生组成的N * N的方阵,为了保证队伍在行进中整齐划一,C君会跟在仪仗队的左后方,根据其视线所及的学生人数来判断队伍是 ...
- android开发里跳过的坑——android studio升级完成后eclipse adt无法正常使用
最近有时间,把android studio做了一次升级,升级完成后,悲催的发现eclipse不能正常运行了,网上查了好多资料,试了很多方法都不行,最后把eclipse使用的sdk与AS使用的SDK区分 ...
- poj_2506_Tiling_201407211555
Tiling Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 7509 Accepted: 3672 Descriptio ...