加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Web系列:Hibernate 基础

发布时间:2020-12-14 06:26:42 所属栏目:Java 来源:网络整理
导读:从以下5个方面学习hibernate ORM。 (1)配置文件:hibernate.cfg.xml XML文件和hibernate.properties属性文件 (2)实体映射:1对多、多对多 (3)会话工厂与会话:SessionFactorySession (4)查询:SQL原生查询、HQL通用查询、Criteria条件查询 (5)事务

从以下5个方面学习hibernate ORM。

(1)配置文件:hibernate.cfg.xml XML文件和hibernate.properties属性文件

(2)实体映射:1对多、多对多

(3)会话工厂与会话:SessionFactory&Session

(4)查询:SQL原生查询、HQL通用查询、Criteria条件查询

(5)事务:Transanction

Hibernate的5个核心对象Conifguration、SessionFactory、Session、Query和Transanction是必须掌握的。另外,没有类似Linq的语言集成查询。

1.配置文件:hibernate.cfg.xml XML文件和hibernate.properties属性文件

Hibernate使用表示配置信息,配置文件的信息最终会适配到Configuration对象。虽然XML文件一直被hibernate支持,但使用hibernate.properties属性文件更简洁。

HSQLDB数据库是一个常用的JAVA版的测试数据库,我们通过下面两种方式演示HSQLDB数据库的配置。其中connection.driver_class,connection.url,connection.username 和 connection.password提供了JDBC使用的数据库链接信息,dialect配置SQL方言,hbm2ddl.auto配置启用自动更新数据库模式,show_sql和format_sql配置便于我们在控制台查看输出信息,generate_statistics配置生成统计信息。

(1)XML方式配置Hibernate:

org.h2.Driver jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE sa org.hibernate.dialect.H2Dialect update true true true

(2)属性文件方式配置Hibernate:

hibernate.connection.url jdbc:h2:mem:db1 hibernate.generate_statistics true

2.实体映射:1对多、多对多

Hibernate的实体映射可以采取XML和代码注解两种, .NET中的EntityFramework的实体映射也有对应的注解(特性)方式,但提供了让实体类更加干净的代码配置方式。无论是依赖注入还是实体映射,Spring和Hibernate在这方面始终相对落后和繁琐。

各种JAVA框架的核心从来不是xml,框架的核心功能和核心对象才是最重要的。注解配置的核心注解如下:

(1)@:标注类为实体。

(2)@和@:前者标注POJO字段为主键,后者标注字段为数据库自动生成。

(3)@和@:在关联字段上标注1对多和多对1。

(4)@:在关联字段上标注多对多,cascade参数指定级联处理规则。

(5)@:标注字段为乐观并发控制版本字段。

下面分别演示常见的1对多、多对多的映射配置。

(1)1对多:Category-Post

Category代码:

List posts = ArrayList setId( .id = Name = List setPosts(List .posts = }

Post代码:

</span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; String Name; </span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; String Text; @ManyToOne </span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; Category category; </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;int</span><span style="color: #000000;"&gt; getId() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; id; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span> setId(<span style="color: #0000ff;"&gt;int</span><span style="color: #000000;"&gt; id) { </span><span style="color: #0000ff;"&gt;this</span>.id =<span style="color: #000000;"&gt; id; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; String getName() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; Name; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; setName(String name) { Name </span>=<span style="color: #000000;"&gt; name; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; String getText() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; Text; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; setText(String text) { Text </span>=<span style="color: #000000;"&gt; text; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; Category getCategory() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; category; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; setCategory(Category category) { </span><span style="color: #0000ff;"&gt;this</span>.category =<span style="color: #000000;"&gt; category; }

}

(2)多对多+乐观锁:User-Role

User代码:

List roles = ArrayList setId( .id = .userName = .password = setVersion( .version = List setRoles(List .roles = }

List users = ArrayList setId( .id = .roleName = List setUsers(List .users = }

3.会话工厂与会话:SessionFactory&Session

(1)会话上下文SessionFactory

始终是Hibernate的核心对象.通过Configuration创建的SessionFactory是Hibernate ORM的核心对象。Hibernate 4.3.5和Hibernate 5.x可以使用一致的代码创建SessionFactory,但5.x需要引入(javax.transaction),否则创建失败。

org.hibernate.cfg.Configuration configuration = configuration.addAnnotatedClass(User. configuration.addAnnotatedClass(Role. configuration.addAnnotatedClass(Category. configuration.addAnnotatedClass(Post. SessionFactory sessionFactory = configuration.buildSessionFactory( }

(2)会话Session

对象类似于EntityFramework中DbContext对象。Hibernate中通过SessionFactory获取Session,有2种方式()和 ()。openSession方式获取单个打开的Session,需要自己写代码关闭。getCurrentSession方式则可以获取自动管理的Session对象,这是依赖CurrentSessionContext接口的实现类来支持的,可以通过配置来适配,取值"jta",""和"managed"分别对应三个实现类。使用getCurrentSession时虽然不需要手动管理Session的关闭,但是需要手动管理Transaction事务的开启和关闭。在Spring中继承Hibernate时,Spring提供了CurrentSessionContext的实现类,避免了我们手动管理事务。在不使用Spring的Servlet环境中,我们可以选择使用Filter+getSession方式使用Session。也可以配置成"thread"+手动管理事务方式。

Filter+getSession可以直接使用click-extras程序包中的Filter和SessionContext,最好是复用并修改其源码,其中SessionContext的实现核心是使用类型为的静态字段实现线程级别的Session共享。

click-extras的pom如下:

org.apache.click click-extras 2.3.0

使用"thread"+手动管理事务方式需要先配置hibernate.properties属性文件:hibernate.current_session_context_class thread。

Query query = factory.getCurrentSession().createSQLQuery("select * from User where userName=?").addEntity(User. User user = }

4.查询:SQL原生查询、HQL通用查询、Criteria条件查询

(1)SQL原生查询:

原生查询使用接口的子接口。通过session可以创建该接口的实例。下面的代码中hsqldb的参数化查询占位符是"?"。为了便于使用,使用了SQLQuery的addEntity方法配置查询对应的实体类型。

Session session = Query query = session.createSQLQuery("select * from User where userName=?").addEntity(User. query.setString(0,"admin" }

(2)HQL通用查询:

Hibernate使用接口,通过自定义的实现通用查询,HQL提供了一个中间语言,屏蔽了不同数据库的语法差异。通过session可以创建Query接口的实例。

Session session = Query query = session.createQuery("from User where userName=:userName" query.setString("userName","admin" }

(3)Criteria条件查询:

Hibernate通过对象提供对自动化查询的方法级别的支持,辅助类Restrictions提供了大量静态方法创建Criteria对象,最大的作用就是防止写错SQL关键字。

Session session = Criteria query = session.createCriteria(User. query.add(Restrictions.eq("userName","admin" }

5.事务

?接口是Hibernate中封装事务的接口,支持JDBC数据库事务和JTA分布式事务,可以通过Session对象使用Transanction进行事务管理。JAT事务则与JTA容器紧密相关,以后再续。

Query query = factory.getCurrentSession().createSQLQuery("select * from User where userName=?" .addEntity(User. User user = }?

参考

(1)http://docs.jboss.org/hibernate/orm/5.0/quickstart/html/

(2)https://www.ibm.com/developerworks/cn/java/j-lo-jta/

(3)https://www.ibm.com/developerworks/cn/java/j-lo-hibernate3/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读