在上一篇文章Hibernate
之 Why? 中对Hibernate有了一个初步的了解.接下来我们将从How的角度,也就是如何使用Hibernate来进行学习.
-
Hibernate是一个开源框架,而我们在项目中使用框架的时候都要对所使用的框架进行相关的环境搭建,下面的步骤便是.
-
创建一个Java项目Hibernate_first
-
创建User
Library,从Hibernate核心文件中加入依赖包.
- HIBERNATE_HOME/hibernate3.jar
UserLiberty部分截图
-
创建核心配置文件hibernate_cfg.xml
-
配置数据库适配器.可以直接使用相关数据库的相关特点.
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库名称地址 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
<!-- 数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库密码 -->
<property name="hibernate.connection.password">root</property>
<!-- 配置数据库适配器.可以直接使用相关数据库的相关特点-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印sql语句到控制台 -->
<property name="hibernate.show_sql">true</property>
<!-- 对打印的Sql语句进行格式化 -->
<property name="hibernate.format_sql">true</property>
<!-- 对资源进行映射 -->
<mapping resource="com/tgb/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
-
环境搭建完毕之后,接下来我们将会用面相对象的思想来完成对数据库表的创建.和我们以前的先建表有所不同,Hibernate是将类映射到关系库数据中的表.接下来建立User类.
package com.tgb.hibernate;
import java.util.Date;
/**
*
* @title 创建User类
* @author jnqqls
* @group TGB
* @version 1.0
* @datetime 2012-11-30上午10:15:25
* @comments
*/
public class User {
//编号
private String id;
//姓名
private String name;
//密码
private String password;
//创建时间
private Date createTime;
//失效时间
private Date expireTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getExpireTime() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
}
-
接下来是Hibernate中核心的地方:建立映射文件User.hbm.xml.如何将一个类映射成数据库中的一个表?它们之间的映射模型如下
-
创建映射文件User.hbm.xml并完成相关映射.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- class标签表示所要映射的java类,而table属性可以更改它在数据库中表的名字,默认是类名 -->
<class name="com.tgb.hibernate.User" >
<!-- 表的主键,有着不同的生存策略 -->
<id name="id">
<generator class="uuid"></generator>
</id>
<!-- 以下内容是对类的属性进行映射 -->
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>
-
类建好,映射也完成,那么如何将类转化成数据库中的实际表呢?接下来我们将会把User类导入数据库表
-
为了让Hibernate识别实体类.需要将User.htm.xml加入核心配置文件Hibernate.cfg.xml中.
- <mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>
-
编写工具栏ExportDB.java,将我们描述的htm文件生成ddl.也就是hbm2ddl
-
package com.tgb.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
*
* @title 将hbm生成ddl 将我们描述的htm文件生成ddl.也就是hbm2ddl
* @author jnqqls
* @group TGB
* @version 1.0
* @datetime 2012-11-30上午10:35:54
* @comments
*/
public class ExportDB {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//读取配置文件上面的信息
Configuration cfg = new Configuration().configure();
//将配置文件写成ddl.
SchemaExport export = new SchemaExport(cfg);
//将ddl打印大控制台并写入数据库中.
export.create(true, true);
}
}
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
drop table if exists User
create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime datetime, expireTime datetime, primary key (id))
-
建立客户端Client,添加用户数据到Mysql.
package com.tgb.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 客户端程序
* @author jnqqls
* @group TGB
* @version 1.0
* @datetime 2012-11-27上午9:31:32
* @comments
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// 读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
// 建立SessionFactory,对应一个数据库的镜像.
SessionFactory factory = cfg.buildSessionFactory();
// 获得session
Session session = null;
try {
// 工厂创建session,并获得.
session = factory.openSession();
// 手动开启事务
session.beginTransaction();
// 创建User实体
User user = new User();
user.setName("jnqqls");
user.setPassword("jnqqls");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
// 保存user对象
session.save(user);
// 提交事务
session.getTransaction().commit();
} catch (Exception e) {
// 这里只是简单打印一下堆栈,用于测试
e.printStackTrace();
//事务回滚.
session.getTransaction().rollback();
} finally {
// session是否为null
if (session != null) {
// session是否打开
if (session.isOpen()) {
// 关闭session
session.close();
}
}
}
Hibernate:
insert
into
User
(name, password, createTime, expireTime, id)
values
(?, ?, ?, ?, ?)
总结:使用Hibernate可以让我们通过面向对象的思维来操作关系型数据库.并且在此文的实例中也有体现出在上一篇文章所谈到的Hibernate优点,例如原来插入数据的insert语句(console所打印的语句)现在只需要一句session.save(user)变能完成相同的功能.至此本文从Hibernate如何使用的角度介绍完毕,在接下来的文章中会继续对Hibernate中的内容进行学习和分享.
分享到:
相关推荐
Then you will learn how to start with Hibernate Search, how to prepare and index your domain model, how to query your data. We will explore advanced concepts like typo recovery, phonetic ...
How to use JPA with Hibernate provider in Eclipse 3.4
In addition, the new and significantly improved EJB 3.0 Java Persistence standard, and how Hibernate implements it, is covered completely. All possible basic and advanced Hibernate mappings are shown...
Hibernate Recipes, 2nd Edition contains a collection of code recipes and templates for learning and building Hibernate solutions for you and your clients, including how to work with the Spring ...
What you’ll learn How to build enterprise Java-based transaction-type applications that access complex data with Hibernate How to work with Hibernate 4 Where to integrate into the persistence life ...
Get started with the Hibernate 5 ...Experienced Java developers interested in learning how to use and apply object-relational persistence in Java and who are new to the Hibernate persistence framework.
Learn how to use the core Hibernate APIs and tools as part of the Spring Framework. This book illustrates how these two frameworks can be best utilized. Other persistence solutions available in Spring...
write transactional applications, and how Hibernate can load data from the database most efficiently. With part 4, “Writing queries,” we introduce the data query features and cover query languages ...
The basics of object-relational mapping and how Hibernate is best suited for it How to do various mappings, including one-to-one mapping, many-to-one mapping, collection mapping, component mapping, ...
a book about how to use the hibernate API
A sample Java web application that demonstrates how <br>Deployment : * Install Dekoh desktop * Start dekoh in interactive mode by executing dekoh_shell.bat / dekoh_shell.sh in directory C:...
Experienced Java developers interested in learning how to use and apply object-relational persistence in Java and who are new to the Hibernate persistence framework. Table of Contents Chapter 1: An ...
GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 ... 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies ...
Learn how to use the core Hibernate APIs and tools as part of the Spring Framework. This book illustrates how these two frameworks can be best utilized. Other persistence solutions available in Spring...
Hibernate: A Developer's Notebook shows you how to use Hibernate to automate persistence: you write natural Java objects and some simple configuration files, and Hibernate automates all the ...
Welcome to the MyEclipse Hibernate and Spring tutorial. This tutorial is meant to be a quick overview of how using both Hibernate and Spring in the same project works in MyEclipse.
What is hibernate Why hibernate How to build a sample The 3 states of PO What hide behind the operation Flush and clear Cache Associations Annotation
http://how2j.cn/k/hibernate/hibernate-tutorial/31.html学习网址
How This API Document Is Organized This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows. Overview The Overview page ...
NULL 博文链接:https://samueli.iteye.com/blog/287194