您的位置:首页 > 职场人生

码农小汪-Hibernate学习1-Start of Hibernate

2016-03-27 19:16 477 查看
把面向对象的软件和关系型数据库一起使用可能是相当麻烦和浪费时间

的。Hibernate 是一个面向 Java 环境的对象/关系型数据库映射工具。对象/关系型数据库映射(object/relational mapping,ORM)这个术语表示一种技术,用来把对象模型表示的对象映射到基于 SQL 的关系模型数据结构中去Hibernate 不仅管理 Java 类到数据库表的映射(包括 Java 数据类型到 SQL 数据类型的映射),还提供数据查询和获取数据的方法,可以大幅度减少开发时对人工使用 SQL 和 JDBC 处理数据的时间。Hibernate 的目标是对于开发者通常的数据持久化相关的编程任务,解放其中的 95%。对于以数据为中心的程序来说,它们往往只在数据库中使用存储过程来实现商业逻辑,Hibernate 可能不是最好的解决方案;对于那些在基于 Java 的中间层应用中,它们实现面向对象的业务模型和商业逻辑的应用,Hibernate 是最有用的。不管怎样,Hibernate 一定可以帮助你消除或者包装那些针对特定厂商的 SQL 代码,而且帮助你结果集从表格式的表示形式转换到一系列的对象中去。

Part 1 - The first Hibernate Application 我觉得中文翻译过来不好听

we create a class that represents the event we want to store in the database; it is a simple JavaBean class with some properties:

就和我们简单的东西一样的,非常的适合我们去处理数据表中的关系哦。我曾经也是学习过SQL的教程的,真正的简历表的过程还是复杂的,当时对于熟悉了原始建表的同志们也是没得问题的,我们可以使用逆向工程班助我们建立Entity的,非常的方便我们去使用。有的喜欢注解的方式,有的喜欢XML的方式,人个有爱吧,都行。

public class Event {
private Long id;

private String title;
private Date date;

public Event() {}

public Long getId() {
return id;
}

private void setId(Long id) {
this.id = id;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}


所有的持久化实体(persistent entity)类(这里也包括一些次要依赖类)都需要一个这样的标识符属性。而事实上,大多数应用程序(特别是 web 应用程序)都需要通过标识符来区别对象,所以你应该考虑使用标识符属性而不是把它当作一种限制。然而,我们通常不会操作对象的标识(identity),因此它的 setter 方法的访问级别应该声明 private。主键懂吧!这个就是id的意思!没学过数据库的童鞋们还是先去看看数据库了再说。

The mapping file(映射文件) 怎么去寻找实体类??哪些是实体类呢?

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

The basic structure of a mapping file looks like this:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping package="org.hibernate.tutorial.domain">

<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
</class>

</hibernate-mapping>


id就是相当于我们表中的主键,然后通过自动生成的策略,colmn.表示映射到数据库中的那个列中。

Hibernate 无法知道这个属性(java.util.Date 类型的)应该被映射成:SQL date,或 timestamp,还是 time 字段。在

此例中,把这个属性映射成 timestamp 转换器,这样我们预留了日期和时间的全部信息。有些还是可以估计的,一般情况下不需要特别的设置的。

这些东西不需要记住的,自己知道就行了,可以在文档中查找的,文档是个非常好的东西,写的很详细的。copy_and_use!

At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate. First let’s set up HSQLDB to run in “server mode”

For Hibernate’s configuration, we can use a simple hibernate.properties file, a more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file

没事的,我就copy了一下子,自己就可以使用啦,很多的,我们要学会看文档,很多的毛病都是对于文档不了解,百度虽说快一点,当是自己学习最好的途径就是文档。

<?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>

<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
这个属性很重要,我们在使用的时候可以看到我们的插入删除不的sql语句哦。
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
这个属性,我们可以在运行程序的时候自己创建我们的表,这里有几个属性,我们一般使用update.我们前面也写过一个博客,可以自动的创建数据表
<property name="hbm2ddl.auto">update</property>

<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>

</session-factory>

</hibernate-configuration>


您配置Hibernate的SessionFactory。 SessionFactory是一个全球性的 工厂负责一个特定的数据库。 如果你有几个数据库,更容易 启动您应该使用一些配置 几个配置文件。

是时候来加载和储存一些 Event 对象了,但首先我们得编写一些基础的代码以完成设置。我们必须启动 Hibernate,此过程包括创建一个全局的 SessoinFactory,并把它储存在应用程序代码容易访问的地方。SessionFactory 可以创建并打开新的 Session。一个 Session 代表一个单线程的单元操作,org.hibernate.SessionFactory 则是个线程安全的全局对象,只需要被实例化一次。我们将创建一个 HibernateUtil 辅助类(helper class)来负责启动 Hibernate 和更方便地操作org.hibernate.SessionFactory。让我们来看一下它的实现:

HibernateUtil.java 每一次数据库的操作就是得到一个session对象,我们可以把一些简单的操作集成进去,比如通过一个HQL语句查询返回一个List,比如查询所有的表的结果,比如我们可以查询数据表在所有的记录中的起始点,到最大值得查询,都可以集成进去。前面有些过一篇博客,里面有贴过代码的。非常的实用。学会封装是我们非常想要的。这个可以让我们在使用Dao,Daoimpl的实现跟加的简单,可以适合操作。在使用spring集成的时候,我们就不用自己采用编程的方式创建工厂了,其实道理差不多

package org.hibernate.tutorial.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}


Loading and storing objects 记载和使用对象。意思就是我们操纵实体对象,直接插入进去,因为Hibernate已经给我们封装好了,我们没有必要采用insert语句,想想都复杂,得到session对象后,直接一个save就行了。

Session session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();

Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);

session.getTransaction().commit();


ok,就是这样子的,新手可能看上去有点累,我也没写清楚,比如数据库的安装,之类的东西。数据库的连接。我们怎么测试呢,写一个Juni使用起来就是特别方便的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: