NHibernate初学实例

合集下载

hibernate简单实例

hibernate简单实例

Hibernate 学习-----创建第一个简单的hibernate程序应用数据库:MySQL工具Myeclipse1数据库中创建数据库bookstore,建立一个表books2 建立一个java projectSrc里面创建一个包com.dao,创建一个类Book (与数据库中表的字段相匹配的类)代码:Book.javapackage com.daoimport java.sql.Timestamp;public class Book{private Integer id;private String name;private String author ;private Timestamp;//声明私有变量与数据库中字段一致,对于主键变量类型尽量使用包装类。

//使用包装类原因:对于id,假如使用int类型,当输入Id为空时,java默认初始化id值为//0,而integer则默认初始化为null。

public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}public Timestamp getCreat_time() {return creat_time;}public void setCreat_time(Timestamp creat_time) {this.creat_time = creat_time;//使用工具自动生成各个变量的set和get方法}}3 com.dao包下创建一个配置文件,告诉hibernate类对应的表即创建类与表之间的映射关系文件创建Book.hbm.xml (注hbm hibernate mapping)内容:<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""/hibernate-mapping-3.0.dtd"> //前面是固定,不需要改变<!----><hibernate-mapping ><class name="com.dao.Book" table="books" lazy="false">//class name指出类的路径,table数据库表的位置<id name="id" type="int" column="id" ><generator class="increment"/></id>//主关键字字段必须用id表示//name 类中的变量名称,type 类型,colum 表中字段名//Generator主关键字产生器 class=”increment”自增长类型<property name="name" not-null="true" column="name"/> //其他字段用property声明其他一致<property name="author" not-null="true"column="author"></property><property name="price" not-null="false"column="price"></property><property name="creat_time" not-null="true"column="creat_time"></property></class></hibernate-mapping>4 创建hibernate配置文件hibernate.cfg.xml在classpath中,即在src根目录下创建hibernate.cfg.xml告诉hibernate要连接的数据库具体信息代码:<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><propertyname="connection.driver_class">com.mysql.jdbc.Driver</property>//数据库驱动<propertyname="connection.url">jdbc:mysql://localhost:3306/bookstore</property> //操作url<property name="ername">root</property>//数据库用户名<property name="connection.password">158655</property>//数据库用户密码<property name="show_sql">true</property>//是否把执行信息打印在控制台<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/dao/Book.hbm.xml"/>//指向路径。

hibernate登录小例子

hibernate登录小例子

一个hibernate的小例子。

最近在学习Hibernate,从网上找了些文章,很难找到图文版单独讲解的,所以自己写了个小例子,希望能给初学者带来点帮助!使用工具为:MyEclipse 6.5 、Tomcat 6.x、,SQL Server20001.先建立一个web project项目:test点击finish,完成web project项目创建。

2.建立数据库的连接windows——> show view——> other——>DB Browser打开后DB Browser后,new一个新的Database Driver,数据库连接驱动对象其中:Driver template是使用的哪种数据库Driver name 是连接对象名,随便起Connection URL数据库连接字符串User name 、password数据库的账号、密码Driver JARs sqlserver2000的连接jar包加上连接jar包后,Driver classname 就会自动显示选择Save password ,然后点击Test Driver,测试下驱动,出现如下图则成功。

点击NextDisplay all schemas 显示所有数据库图形界面Dislpay default …….. 显示默认的数据库的界面,即你在驱动对象中连接的数据库:DatabaseName=ddsql,也就是ddsql。

Display the selected schemas 手动选择数据库,点击Add选择,最好使用这个选择数据库。

选择好后,点击Finish。

3.在项目中加载Hibernate点击Next继续,点击Next,在出来的界面中DB Driver中选择我们使用的数据库,如图点击Next点击new一个新的包com.jnycsl.hibernate,然后Finish。

这样,出现hibernate.cfg.xml的图形显示,点击source<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="ername">sa</property><propertyname="connection.url">jdbc:microsoft:sqlserver://localhost:1433;Datab aseName=ddsql</property><propertyname="dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="myeclipse.connection.profile">test</property><property name="connection.password">sa</property><propertyname="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServer Driver</property></session-factory></hibernate-configuration>4,使用hibernate,打开DB Browser,从test中选择一个表usersUsers表字段如下:字段名类型约束备注id int 主键自增长,标识列loginid varchar 非空password varchar 非空name varchar 非空点击,下面界面如下选择Java src folder 选择的当然是本项目的文件夹了Java package 使用的包修改为上图所示点击Next在出现的界面中只是把Id generator 选择为identity就可以了,在点击next,在出现的界面中直接选择Finish结束。

hibernate官方入门教程

hibernate官方入门教程

hibernate官方入门教程第一部分-第一个Hibernate程序首先我们将创建一个简单的控制台(console-based)hibernate程序。

我们使用内置数据库(in-memory database) (HSQL DB),所以我们不必安装任何数据库服务器。

让我们假设我们希望有一个小程序可以保存我们希望关注的事件(Event)和这些事件的信息。

(译者注:在本教程的后面部分,我们将直接使用Event而不是它的中文翻译“事件”,以免混淆。

)我们做的第一件事是建立我们的开发目录,并把所有需要用到的Java库文件放进去。

从Hibernate网站的下载页面下载Hibernate分发版本。

解压缩包并把/lib下面的所有库文件放到我们新的开发目录下面的/lib目录下面。

看起来就像这样:.+libantlr.jarcglib-full.jarasm.jarasm-attrs.jarscommons-collections.jarcommons-logging.jarehcache.jarhibernate3.jarjta.jardom4j.jarlog4j.jarThis is the minimum set of required libraries (note that we also copied hibernate3.jar, the main archive) for Hibernate. See the README.txt file in the lib/ directory of the Hibernate distribution for more information about required and optional third-party libraries. (Actually,Log4j is not required but preferred by many developers.) 这个是Hibernate运行所需要的最小库文件集合(注意我们也拷贝了Hibernate3.jar,这个是最重要的库)。

Hibernate教程_从入门到精通_第二篇(共四篇)

Hibernate教程_从入门到精通_第二篇(共四篇)
第二章 Hibernate API
目标: •Hibernate API简介
Hinernate的体系结构(运行时)





SessionFactory:它保存了对当前数据库配置的所有映射关系,它是将某 个数据库的映射关系经过编译之后全部保存在内存中的。 它还是生成 Session的工厂,它在进行实例化的过程中将会用到ConnectionProvider。 一个SessionFactory对应一个数据库连接,当数据库连接改变时需要修改 SessionFactory Sesion: 是进行持久化操作的基础,所有的持久化操作都是在Session的 基础上进行的。它相当与JDBC中的Connection。它是Hibernate的持 久化 管理器的核心,提供了一系列的持久化操作方法。另外,它还持有一个针 对持久化对象的一级缓存,在遍历持久化对象或者根据持久化标识查找对 象的时候会用 到。 Transation:功能上和数据库中的事务完全一样,通过它实现对数据库中 事务的控制。Transation对象是Session对象产生的,所以他的生命周期比 Session短。一个Session的生命周期中可以有多个Transaction对象。 ConnectonProvider:主要作用是生成与数据库建立了连接的JDBC对象 ,同时他还作为数据库连接的缓冲池。通过ConnectionProvider实现了应 用程序和底层的DataSource和DriverManager的隔离。 TransactionFactory:是生成Transaction对象的工厂,通过 TransactionFactory实现了事务的封装,使其具体的实现方法与应用程序无 关。

判断一个实体对象是否处于瞬态: 该实体对象的<id>属性(如果存在)的值为空 如果在映射文件中为<id>设置了unsaved-value属性,并且 实体对象的id属性的值与unsaved-value属性的值相同 如果这个实体对象配置version属性,并且version属性的 空 在映射文件中为version属性设置了unsaved-value属性,并且 version属性的值与unsaved-value属性的值相同。 如果设置了interceptor,并且interceptor的isUnsaved() 方法的返回值为true

hibernate 简单实例

hibernate 简单实例

简单的hibernate数据库插入例子刚刚开始学习,希望和大家一起进步吧。

请大家不要笑我。

这是一个最简单的例子,该例子基本上是按照hibernate reference来做的。

做这个例子我选用的应用服务器是山东中创软件商用中间件有限公司的InforWeb(这个应用服务器是商用的,如果你无法获得它,那么可以用tomcat代替),数据库我选用的是Oracle,你可以选用小巧的MySql。

首先你需要Hibernate2.0 相关运行环境,可以从 /下载;第一步:下载hibernate.第二步:在InforWeb的deploy(tomcat中是webapps)目录下先新建一个应用,目录如下:%InforWebHome%/deploy/cat。

第二步:将数据库的驱动程序加入到CLASSPATH中,或者将驱动拷贝到%InforWebHome%/lib下(tamcat下是%tomcatHome%/common/lib);第三步:把Hibernate提供的hibernate2.jar(根目录下)和一些第三方的运行库拷贝到hibernate\WEB\INF\lib目录下。

(这些第三方的运行库包含在下载的Hibernate lib目录下)。

下面对几个必须的包做一下解释:dom4j:hibernate解析xml配置和映射元文件时需要使用。

Cglib:hibernate运行时使用这个代码生成库强化类。

Collections,Commons Logging:ODMG4:Hibernate 提供了一个可选的ODMG 兼容持久化管理界面。

如果你需要映射集合,你就需要这个类库,就算你不是为了使用ODMG API。

我们在这个教程中没有使用集合映射,但不管怎样把这个JAR 拷贝过去总是不错的。

虽然这几个文件是必须的,但是还是把所有的包都拷贝过去吧,这样比较保险啊,:)。

第四步:你可以通过InforWeb管理工具配置应用、给应用添加数据源,如果你对部署描述符比较熟悉的话就直接修改server.xml吧。

1 Hibernate入门

1 Hibernate入门

加载并存储对象
public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); mgr.createAndStoreEvent("My Event", new Date()); HibernateUtil.getSessionFactory().close(); } private void createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); } }
– column属性则告诉Hibernate, 我们使用EVENTS表的 哪个字段作为主键。嵌套的generator元素指定了标识 符生成策略,在这里我们指定native,它根据已配置的 数据库(方言)自动选择最佳的标识符生成策略。
映射文件
• 和id元素一样,property元素的name属性告诉 Hibernate使用哪个getter和setter方法。在此例中, Hibernate会寻找getDate()/setDate(), 以及 getTitle()/setTitle()。 • 为什么date属性的映射含有column attribute,而 title却没有?当没有设定column attribute 的时候, Hibernate缺省地使用JavaBean的属性名作为字 段名。对于title,这样工作得很好。然而,date在 多数的数据库里,是一个保留关键字,所以我们 最好把它映射成一个不同的名字。

NHibernate基本教程

NHibernate基本教程

•NHibernate(1)-試驗 試驗版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明 /logs/75393398.html一、試驗架構圖如右 1 添加引用:NHibernate.dll、Iesi.Collections.dll, 編譯後,會自動生成 Castle.Core.dll、Castle.DynamicProxy2.dll、log4net.dll 2 使用 NHibernateProfier 探查 HQL 語句: 執行 NHibernateProfier 的探查功能,需要在應用程序裡面配置相關信息。

首先,我們需要添加 HiberHibernatingRhinos.Profiler.Appender.dll 的引用。

該文件在 NHibernateProfier 安裝目錄下可找到。

接著,我們配置 log4net:於 web 層目錄下創建 log4net.config 文件: <?xml version="1.0" encoding="utf-8"?> <log4net> <appender name="NHProfAppender" type="HibernatingRhinos.Profiler.Appender.NHibernate.NHProfAppender, HibernatingRhinos.Profiler.Appender"> <sink value="http://localhost"/><!--注意,這裡應用程序 web 地址--> </appender> <logger name="HibernatingRhinos.Profiler.Appender.NHibernate.NHProfAppender.Setup"> <appender-ref ref="NHProfAppender"/> </logger> </log4net> 最後,在 Global.asax 全局文件中添加語句: void Application_Start(object sender, EventArgs e) { //在应用程序启动时运行的代 码 } 3 DAL 層 SessionManager.cs using NHibernate; using NHibernate.Cfg; namespace Siuben.NH.DAL { public class SessionManager { private ISessionFactory _sessionFactory; public SessionManager() { _sessionFactory = GetSessionFactory(); } private ISessionFactory GetSessionFactory() { return (new Configuration()).Configure().BuildSessionFactory(); } public ISession GetSession() { return _sessionFactory.OpenSession(); } } } 4 Model 層說明: HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();Entities: namespace Siuben.NH.Model { public class Customer { public virtual int ID { get; set; }//Virtual 必須 public virtual string FirstName { get; set; } public virtual string LastName { get; set; } } } Mappings: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Siuben.NH.Model" namespace="Siuben.NH.Model"> <class name ="Siuben.NH.Model.Customer,Siuben.NH.Model" table="Customer"> <id name="ID" column="ID" type="Int32" unsaved-value="0"> <generator class ="native"></generator> </id> <property name="FirstName" column ="FirstName" type="string" length="50" not-null="false"/> <property name ="LastName" column="LastName" type="string" length="50" not-null="false"/> </class> </hibernate-mapping>•NHibernate(2)-HQL版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明 /logs/75408876.html1.from 子句顾名思义,同 SQL 语句类似:(注意有不同的地方:HQL 和 SQL 的關鍵字不區分大小寫,而 HQL 中 c.CustomerId 和 c.customerid 是不同的 正確的寫法是 CustomerId 要與 Model 層 Customer 對象的 CustomerId 屬性大小寫相同,原因很簡單,HQL 就是面向對象的查詢) 1.简单用法:返回表中所有数据。

一个简单的hibernate实例(之一)

一个简单的hibernate实例(之一)

1. <?xml version="1.0" encoding='utf-8'?>2. <!DOCTYPE hibernate-mapping PUBLIC3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"4. "/hibernate-mapping-3.0.dtd">5.6. <hibernate-mapping>7. <class name="er" table="users">8. <id name="id">9. <generator class="identity"/>10. </id>11. <property name="name"/>12. <property name="password"/>13. <property name="email"/>14. </class>15. </hibernate-mapping>在数据库中建立一个myproject(按你的意思定名)数据库,在其中建立一个users表(向RoR学习):1. CREATE TABLE `users` (2. `id` int(11) NOT NULL auto_increment,3. `name` varchar(255) default NULL,4. `password` varchar(255) default NULL,5. `email` varchar(255) default NULL,6. PRIMARY KEY (`id`)7. )注:我是用phpmyadmin对mysql数据库进行管理的,在建立的时候我特意为其选择了utf-8编码。

Hibernate简单示例

Hibernate简单示例

Hibernate简单示例Hibernate是非常典型的持久层框架,持久化的思想是非常值得我们学习和研究的。

这篇博文,我们主要以实例的形式学习Hibernate,不深究Hibernate的思想和原理,否则,一味追求,苦学思想和原理,到最后可能什么也学不会,从实践入手,熟能生巧,思想和原理自然而然领悟。

一、开发环境Win8 + jdk1.7 + MyEclipse + Tomcat5.0 + MySQL说明:其实Hibernate是非常独立的框架,根本不需要MyEclipse,Eclipse,Tomcat,Log4J等,他们只不过是能满足我们其他的需求,才把他们引进来的。

二、下载文件你需要Java SDK、Hibernate包、和JDBC Driver。

1、Hibernate包下载地址:/hibernate/?sort_by=date&sort=desc2、JDBC Driver根据你的数据库来定,一般database官网都有。

Hibernate支持常用的数据库,比如MySQL,Oracle 等等。

这两个数据库是现在比较常用的,都有JDBC Driver:Oracle JDBC Driver下载地址(下载前必须同意Oracle协议书)/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.htmlMySQL JDBC Driver下载地址/downloads/connector/j/3.0.html三、所需jar包hibernate3.jar Hibernate的核心包dom4j-1.6.1.jar dom4j读取xml文件包mysql-connector-java-3.1.13-bin.jar MySQL的jdbc驱动包Hibernate的作用:让我们以面向对象的方式或思维来考虑怎么向关系型数据库存取数据。

个人总结Hibernate+struts实例学习过程

个人总结Hibernate+struts实例学习过程

这篇文章本来是要在昨天睡觉之前发上来,但是家里的网速实在是让我郁闷,刚忙完工作偷空上来赶紧发了,还有一点让我郁闷的就是JavaEye的这个编辑器不是太好用,在word里面写好的内容不能全部粘贴过来,文档中有很多图片,需要一张张上传,然后在加上来!痛苦。

以后还是少截图。

不说了,还是赶紧发文章吧!1、数据库设计建立crud.student数据库表:图1 数据库表你可以使用如下语句创建该库表:Sql代码1.create database if not exists `crud`;E `crud`;3.DROP TABLE IF EXISTS `student`;4.CREATE TABLE `student` (5. `id` int(4) NOT NULL auto_increment,6. `name` varchar(20) default NULL,7. `age` int(4) default NULL,8. `score` int(4) default NULL,9. PRIMARY KEY (`id`)10.) ENGINE=InnoDB DEFAULT CHARSET=utf8;在这里我使用的是SQL Server2000数据库,当然你也可以选择别的数据库,只是在选择之前请准备好相应的jar包即可。

2、程序编写:第一步:配置数据源1、打开MyEclipse,新建一个web工程,这里命名为hibernate_demo2、打开数据库设置器:依次单击【window】-->【Show View】-->【Other…】如下图所示:3、在弹出的窗口ShowView中选择DB Browser,如下图所示:4、在DB Browser窗口中,选择显示的图标,单击右键执行新建命令,如下图示5、弹出Database Driver对话框,在此会要求我们配置数据库的相关信息,具体设置如下图所示,设置完成,单击Finish.(Connection URL填写:jdbc:microsoft:sqlserver://localhost:1433 Driver IARS:加入SQL Server 的那三个jar包)【第二步】引入hibernate配置文件1、添加hibernate包:选中我们的Web工程,依次单击鼠标右键-->MyEclipse-->Add Hibernate Capabilities… 如下图所示:2、在弹出的窗口中做如下设置:【Next】【Next】单击Next,把要创建的SessionFactory放置于相应的包中,如果前面没有设置包名,这里要先单击New创建新的包。

Hibernate入门笔记

Hibernate入门笔记

一、第一个应用实例1. 搭建环境;新建一个名为HibernateDemo 的java L 程,并导入Hibernate 的jar 包, 特别要注意除了导入lib 下的jar 包还需导入核心jar 包。

曲于涉及数据库操作,还应 导入mysql 驱动包。

说明,如果使用最新的hibernatehibernate 的基本jar 包(7个)来源:13.2lib\required 下的所有jar 包2. 简述 Hibernate 的作用:ORM : Object Relational Mapping» 对象关系映射。

将 jas 程序中的对象自动持久化到关系数®库中。

而Hibernate 的作用好比就是在java 对象与 关系数据库之间的一座桥梁,它主要负责两者之间的映射。

在Hibernate 内部封装了 JDBC 技术(但只是一个轻量级的封装,因而可以让程序设计人员更方便的以面向对象的思想操 纵数据库),并向外提供API 接口。

3. 建新一个名为的类,即是上面所说的java 对象。

我们以后称这种类为实体类(或持 久化类),它的对象为实体对象(或是持久化对象)。

内容如下:packagepublic int getIdO { return id;public void setld(int id) { =id;public String getName() { return name;public void setName(String name) { =name;public Date getDateO { return date;public void setDate (Date date) { =date;4. 编写配置文件:。

它和放在同一个包下。

内容如下:<xml version=""〉<!DOCTYPE hibernate-mapping PUBLIC"-体类定义规则:Domain object (java 对象)必须要有构造方法,同时建议有一个id 属性,为了赖加载, 这个java 类的声明最好不用finalo8•开发流程: private private class User{ int id;String name;private Date date;官方推荐:先Domain object 再mapping,最后是DB 。

Hibernate入门_1

Hibernate入门_1

类的映射文件第二种格式
<hibernate-mapping> <class name=" com.pojo.Emp " table="emp"> <id name="id" type="ng.Integer" column="id"> <generator class="increment"/> </id> <property name="empname" type="ng.String" column="empname"/> <property name="salary" type="ng.Double" column="salary"/> <property name="hiredate" type="java.util.Date" column="hiredate"/> </class> </hibernate-mapping>
创建实体类Emp.java
package com.pojo; import java.util.Date; public class Emp implements java.io.Serializable { private Integer id; private String empname; private Double salary; private Date hiredate; public Emp() { } public Emp(Integer id) { this.id = id; } public Emp(Integer id, String empname, Double salary, Date hiredate) { this.id = id; this.empname = empname; this.salary = salary; this.hiredate = hiredate; } get和set方法略 }

NHibernate初学实例

NHibernate初学实例

6 在 web 项目中添加 Model 和 BLL 的引用。
接着添加页面 User.aspx,前台的现实我们使用 repeater 控件 <asp:Repeater ID="rptUserInfo" runat="server"> <HeaderTemplate> <table id="tblUserInfo" border="0" width="100%" cellp adding="0" cellspacing="1">
} finally { session.Close(); } } public bool Delete(UserInfo userInfo) { Configuration cfg = new Configuration().Configure(path);
ISession session = cfg.BuildSessionFactory().OpenSessio n(); ITransaction transaction = session.BeginTransaction(); try { session.Delete(userInfo); mit(); return true; } catch (Exception e) { transaction.Rollback(); return false; } finally { session.Close(); } } public UserInfo GetUserInfoById(int userId) { Configuration cfg = new Configuration().Configure(path); ISession session = cfg.BuildSessionFactory().OpenSessio n(); return session.Get<UserInfo>(userId); } }

Hibernate入门示例

Hibernate入门示例

Hibernate 入门示例Copyright Notice Copyright© 2003 - 2005 Gillion Technologies Ltd. No part of this publication may be copied without the express writtenPermission of Gillion Technologies Ltd.Document ID GS_GFA_T_TEC _05-01-25_1 Revision 0.1Confidential Revision HistoryIndex1本文目的 (5)2本文内容概述 (5)2.1开发环境 (5)2.2框架搭建 (5)2.3示例 (5)3框架搭建 (6)3.1 JB和SQL S ERVER的安装 (6)3.2创建PROJECT (6)3.2.1创建一个Project (6)3.2.2在Project中添加package (6)3.3 HIBERNATE和数据库驱动的配置 (7)3.3.1hibernate的配置 (7)3.3.2数据库驱动的配置 (7)3.3.3hibernate.properties的配置 (8)3.3.4hibernate.cfg.xml的配置 (9)3.4 HBM文件自动生成配置 (10)4示例 (10)4.1 ONE-TO-ONE: AUTHOR-----PERSON (11)4.1.1 Step1. 在entity包中添加Author.java (11)4.1.2 Step2. 在entity包中添加Person.java (13)4.1.3 Step3 hbm文件的生成 (15)4.1.4 Step4数据库中表的产生 (15)4.1.5 Step5创建访问接口 (16)4.1.6 Step6访问接口的实现 (18)4.1.7 Step7对实现的测试 (22)4.2 ONE-TO-MANY: AUTHOR-----PUBLICATION (23)4.3 MANY-TO-MANY: AUTHOR----WORK (27)4.4 AUTHOR的查询,更新,删除 (37)5总结展望 (41)6HIBERNATE IN SPRING (43)6.1 概述 (43)6.2 配置 (43)6.3 实现 (43)6.4 总结 (49)1本文目的Hibernate是一个开放源代码的O/R Mapping (对象关系映射框架),它对JDBC进行了轻量级的对象封装,使Java程序员可以随心所欲的使用对象编程思维来操纵数据库。

Hibernate入门课程--编程练习(2)

Hibernate入门课程--编程练习(2)
try{ tx = session.beginTransaction(); Query query = session.createQuery("from Book"); //激活查询缓存 激活查询缓存 query.setCacheable(true); //使用自定义的查询缓存区域 若不设置 则使用标准查询缓存区域 使用自定义的查询缓存区域,若不设置 使用自定义的查询缓存区域 若不设置,则使用标准查询缓存区域 query.setCacheRegion("longTime"); List list = query.list(); for(int i = 0 ; i < list.size(); i++){ Book b1 = (Book)list.get(i); } mit(); }catch(HibernateException e){ e.printStackTrace(); }
Subversion一般分为服务器和客户端两部分。
Subversion服务器一般在官方网站上下载
TortoiseSVN在windows下非常受到欢迎的客户端,可与 资源管理器集成 Subclipse是eclipse/myeclipse上的一个客户端插件
Subversion服务器安装配置
建立版本库(Repository)
EhCache的配置
Hibernate.cfg.xml配置
Book.hbm.xml配置
<cache region="longTime" usage="read-only"/>
创建EhCache.xml
EhCache.xml实例
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="d:/cache" /> <defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="180" timeToLiveSeconds="300" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> <cache name="longTime" maxElementsInMemory="100" eternal="false" overflowToDisk="true" timeToIdleSeconds="1800" timeToLiveSeconds="3000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>

Hibernate使用实例步骤

Hibernate使用实例步骤

Hibernate使用实例步骤用MyEclipse, 就有必要把MyEclipse 快速开发的功能熟悉一下. 当我们熟悉了基本的开发过程之后, 就需要考虑用顺手的 IDE 来让我们的开发速度有个飞跃了.这次讨论的主题包括: Hibernate 快速开发, Spring 快速开发, Struts 登录应用开发, UML 建模, 可视化Swing界面开发这些个内容.首先就是大家可以看 MyEclipse 的帮助文档进行学习了, 里面很全, 图文并茂, 唯一缺点呢就是文档是英文的. 具体方法:菜单 Help -> Help Contents, 然后会在浏览器里打开 MyEclipse 帮助文档, 展开左边的 MyEclipse Learning Center, 就能看到详细的开发教程了. 其中 "JEE Application Development" 的部分是我们重点关注的内容.使用的开发工具是 MyEclipse 5.5.1 GA, Windows/Linux 版本均可.好了, 现在简单介绍一下用 MyEclipse 2 分钟开发一个 Hibernate 应用的步骤.1. 在 MyEclipse 视图下的 Servers 面板上, 启动 MyEclipse Derby 这个服务器. 相信大家都很熟悉这个过程了.2. 选择菜单Window -> Open Persipective -> MyEclipse Database Explorer, 打开新的数据库浏览视图.3. 在最左边的 DB Browser 面板下选中 MyEclipse Derby 项, 点击右键并选择弹出菜单中的菜单项Open Connection 来打开数据库连接并显示所有的数据库和表格.4. 展开 MyEclipse Derby 节点, 单击选中第一项 Connected to MyEclipse Derby, 点击右键并选择弹出菜单中的菜单项New SQL Editor.5. 在 SQL 编辑器里键入下列建表语句:create table testUser(id int not null,username varchar(200),age int,primary key ("ID")), 然后点击编辑器上面的绿色的运行向右箭头按钮来创建表格.6. 新建一个 Java Project 名字为 MyHibernateTest, 这个过程无需赘述了, 建议建项目的时候将 src 目录和 bin(或者classes)目录分开, 另外提示你切换透视图的时候一定要切换过去到Java 透视图, 此时默认会在 Package Explorer 中选中刚才已经建好的 Java Project, 但是背景为灰色.7. 首先单击一下左边的Package Explorer 中新建的MyHibernateTest 项目来使其高亮选中, 接着点击菜单项 MyEclipse -> Add Hibernate Capabilities..., 接着会弹出对话框New Hibernate Project 提示你设置当前项目的 Hibernate 属性.对话框的第一页选择 Hibernate 3.1, 其它保持默认;第二页同样如此, 保持默认来创建新的 Hibernate 配置文件;第三页Specify Hibernate database connection details则点击DB Driver 下拉框选择 MyEclipse Derby, 这时候下面的输入框会自动填好数据库连接对应的值.第四页Define SessionFactory properties 则先点击Java Package 一行最右侧的 New... 按钮来新建一个名字为 dao 的包. 这时候你可以看到Finish 按钮终于不为灰色了, 点击它完成给项目加入Hibernate 开发功能的操作, 包括Hibernate 类库, jdbc 驱动和Hibernate 配置文件都已经设置完毕了.8. 选择菜单Window -> Open Persipective -> MyEclipse Database Explorer, 打开数据库浏览视图. 展开Connected to MyEclipse Derby 下面的 APP 节点, 再选中下面的 TABLE 目录, 点击右键并选择弹出菜单中的菜单项 Refresh 来刷新数据库表格列表, 这时候展开此节点可以看到下面出现了一个名为 TESTUSER 的表.9. OK, 最关键的操作即将开始了. 请在TESTUSER 节点上点击右键并选择弹出菜单中的菜单项 Hibernate Reverse Engineering..., 弹出一个对话框提示你 Save All Modified Resources, 点击 OK 并且选中MyHibernateT est, 在File name 右侧的文件名输入框中输入create.sql 来保存我们最开始所写的那个建表的 SQL 文件.10. 接着 Hibernate Reverse Engineering 对话框弹出了.点击 Java src folder 一行最右侧的 Browser.. 按钮来选择源码目录, 并把下面的 Java package 右侧的输入框中输入包名 dao, 我们选择/MyHibernateT est/src 目录并点击完成, 接着选中下面的三个复选框:[x] Hibernate mapping file (*.hbm.xml) for each database table[x] Java Data Object (POJO <> DB Table)[x] Java Data Access Object (DAO) (Hibernate 3 only)好了, 点击 Finish 按钮, 就可以看到反向工程的忙碌对话框. 最后当一切结束后弹出对话框提示切换视图到MyEclipse Hibernate perspective 的时候点击 "OK" 按钮, 您就可以看到工作成果了, 包括下列文件:HibernateSessionFactory.javaTestuser.hbm.xmlBaseHibernateDAO.javaIBaseHibernateDAO.javaTestuser.javaTestuserDAO.javahibernate.cfg.xml. 那么, 我们的 POJO 已经生成了, 就是 T estuser.java, DAO 的代码也已经生成, 就是 TestuserDAO, 这些代码都已经帮我们写好, 当然我们可以做进一步的修改来适应我们的要求. 当你用工具生成代码的时候, 请确保您已经了解了 Hibernate 手工开发的步骤. 好了, 接下来的事情, 我们就可以11. 修改 Testuser.hbm.xml 里面的主键生成方式为合适的方式(默认的是 <generator class="assigned" />), 或者一些属性映射关系, 这些仍然要求开发人员对 Hibernate 的配置文件有一定的了解;或者12. 继续重复 1, 3, 5, 8, 9, 10 来生成更多的 POJO 或者 DAO.13. 编写测试代码来运行测试.小结: 虽然这些步骤很繁琐, 但是当你熟练之后完全可以在2分钟内完成所有操作, 这样就省去了手工编写大量 Java 代码和 XML 配置文件的痛苦, 这也是实际中程序员采取的偷懒的步骤.前提: 您一定要理解 Hibernate 手工开发的步骤和 JDBC 驱动的概念, 否则生成的文件有时候是有潜在的问题的, 工具只能帮你完成部分工作, 不能完成全部工作.更多提示: 当你执行第9 步的时候, 还可以看到弹出的菜单中有JPA 和 EJB 3 反向工程的选项, 这个就留给大家做练习了, 同样也能生成类似的JPA 或者EJB 3 实体类, 当然您实现要建好支持JPA 或者EJB 的项目.。

NHibernate的第一个例子

NHibernate的第一个例子

Welcome to NHibernateIf you're reading this,we assume that you've just downloaded NHibernate and want to get started using it.This tutorial will talk you through the following:•Installing NHibernate•Defining a simple business object class.•Create an NHibernate mapping to load and save the business object.•Configure NHibernate to talk to your local database.•Automatically generate a database•Writing simple CRUD code using the Repository pattern.•Using Unit Tests to make sure the code is working correctly.This is what we're aiming for:But first things first[:)]Lets start by actually doing something with that ZIP file you just downloaded.Installing NHibernateIf you've downloaded the NHibernate binaries in a zip file,all you need to do is extract that file to somewhere sensible.I usually create a folder called SharedLibs c:\Code\SharedLibs\NHibernate and extract the zip to there.But whatever you're comfortable with.This is your SharedLib folderfrom which you need to add your references to the NHibernate and NUnit dlls.Add references to NHibernate to both the demo project and the unit test project.That's it!NHibernate is installed(easy huh).We'll talk you through using it with Visual Studio in a moment.First let's look at how we go about creating a project.Note this code is dependent on Visual Framework3.5.Create Your ProjectBefore we start building our application and business objects,we'll need to create a blank project to put them in.Fire up Visual Studio and create a new Class Library project.Let's now look at something interesting:creating a business object.Defining the Business ObjectsLets start by defining a very simple domain.For the moment it consists of one entity called Product.The product has3properties Name,Category and Discontinued.Add a folder Domain to the FirstSample project of your solution.Add a new class Product.cs to this folder.The code is very simple and uses automatic properties(a feature of the new C#3.0 compiler)namespace FirstSolution.Domain{public class Product{public string Name{get;set;}public string Category{get;set;}public bool Discontinued{get;set;}}}Now we want to be able to persist instances of this entity in a(relational)database.We have chosen NHibernate for this task.An instance of an entity in the domain corresponds to a row in a table in the database.So we have to define a mapping between the entity and the correspondingtable in the database.This mapping can be done either by defining a mapping file(an xml-document)or by decorating the entity with attributes.I'll start with the mapping file.Define the MappingCreate a folder Mappings in the FirstSample project.Add a new xml-document to this folder and call it Product.hbm.xml.Please note the"hbm"part of the file name.This is a convention used by NHibernate to automatically recognize the file as a mapping file.Define"Embedded Resource" as Build Action for this xml file.In the Windows Explorer locate the nhibernate-mapping.xsd in the src folder of NHibernate and copy it to your SharedLibs folder.We can now use this xml schema definition file when defining our mapping files.VS will then provide intellisense and validation when editing an xml mapping document.Back in VS add the schema to the Product.hbm.xml fileLet's start now.Each mapping file has to define a<hibernate-mapping>root node<?xml version="1.0"encoding="utf-8"?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"assembly="FirstSolution"namespace="FirstSolution.Domain"><!--more mapping info here--></hibernate-mapping>In a mapping file when referencing a domain class you always have to provide the fully qualified name of the class(e.g.FirstSample.Domain.Product,FirstSample).To make the xml less verbose you can define the assembly name(in which the domain classes are implemented and the namespace of the domain classes in the two attributes assembly and namespace of the root node.It's similar to the using statement in C#.Now we have to first define a primary key for the product entity.Technically we could take the property Name of the product since this property must be defined and has to be unique.But it is common to use a surrogate key instead.For thus we add a property to our entity and call it Id.We use Guid as the type of the Id but it can as well be an int or a long.using System;namespace FirstSolution.Domain{public class Product{public Guid Id{get;set;}public string Name{get;set;}public string Category{get;set;}public bool Discontinued{get;set;}}}The complete mapping file<?xml version="1.0"encoding="utf-8"?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"assembly="FirstSolution"namespace="FirstSolution.Domain"><class name="Product"><id name="Id"><generator class="guid"/></id><property name="Name"/><property name="Category"/><property name="Discontinued"/></class></hibernate-mapping>NHibernate doesn't get in our way such as that it defines many reasonable defaults.So if you don't provide a column name for a property explicitly it will name the column according to the property. Or NHibernate can automatically infer the name of the table or the type of the column from the class definition.As a consequence my xml mapping file is not cluttered with redundant information.Please refer to the online documentation for more detailed explanation of themapping.You can find it here.Your solution explorer should look like this now(Domain.cd contains the class diagram of our simple domain).You will have added the design folder and created the class diagram yourself although this is for good practice and not required for the purposes of this excercise.Configure NHibernateWe now have to tell NHibernate which database product we want to use and provide it the connection details in form of a connection string.NHibernate supports many many database products!Add a new xml file to the FirstSolution project and call it hibernate.cfg.xml.Set its property "Copy to Output"to"Copy always".Since we are using SQL Server Compact Edition in this first sample enter the following information into the xml file<?xml version="1.0"encoding="utf-8"?><hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"><session-factory><propertyname="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property><property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property> <property name="connection.connection_string">Data Source=FirstSample.sdf</property><property name="show_sql">true</property></session-factory></hibernate-configuration>With this configuration file we tell NHibernate that we want to use MS SQL Server Compact Edition as our target database and that the name of the database shall be FirstSample.sdf (=connection string).We have also defined that we want to see the SQL NHibernate generates and sends to the database(highly recommended for debugging purposes during development).Double check that you have no typos in the code!Add an empty database called FirstSample.sdf to the FirstSample project(choose Local Database as template)Click Add and ignore the DataSet creation wizard(just hit Cancel).Test the SetupIt's now time to test our setup.First verify that you have the following files in your SharedLibs folderThe last8files you can find in the"Microsoft SQL Server Compact Edition"directory in your Programs folder.Note:the System.Data.SqlServerCe.dll is located in the sub-folder Desktop.All other files can be found in the NHibernate folderAdd a reference to the FirstSample project in your test project.Additionally add references to NHibernate.dll,nunit.framework.dll and Systm.Data.SqlServerCe.dll(remember to reference the files located in the SharedLibs folder!).Pay attention to set the property"Copy Local"to true for the assembly System.Data.SqlServerCe.dll since by default it is set to false!Add a copy of hibernate.cfg.xml to the root of this unit test project.Direct action with NHibernate in the NUnit project needs access to this file.Add a class called GenerateSchema_Fixture to your test project.Your test project should now look like thisWe further need the7files sqce*.dll in the output directory.We can do this by using a post-build event in VS.Enter the following command in the"Post-build event command line"copy$(ProjectDir)..\..\SharedLibs\sqlce*.dll$(ProjectDir)$(OutDir)Now add the following code to the GenerateSchema_Fixture fileusing FirstSolution.Domain;using NHibernate.Cfg;using NHibernate.Tool.hbm2ddl;using NUnit.Framework;namespace FirstSolution.Tests{[TestFixture]public class GenerateSchema_Fixture{[Test]public void Can_generate_schema(){var cfg=new Configuration();cfg.Configure();cfg.AddAssembly(typeof(Product).Assembly);new SchemaExport(cfg).Execute(false,true,false,false);}}}The first line of the test method creates a new instance of the NHibernate configuration class.Thisclass is used to configure NHibernate.In the second line we tell NHibernate to configure itself. NHibernate will look out for configuration information since we do not provide any information here in the test method.So NHibernate will search for a file called hibernate.cfg.xml in the output directory.That's exactly what we want since we have defined our settings in this file.In the third line of the code we tell NHibernate that it can find mapping information in the assembly which contains also the class Product.At the time being it will only find one such file (Product.hbm.xml)as an embedded resource.The fourth line of code uses the SchemaExport helper class of NHibernate to auto-"magically" generate the schema in the database for us.SchemaExport will create the product table in the database and each time you call it it will delete the table and the table data and recreate it.Note:with this test method we do NOT want to find out whether NHibernate does its job correctly (you can be sure it does)but rater whether we have setup our system correctly.However,you can check the database and see the newly created'product'table.If you have installed you can now just right click inside the test method and choose"Run Test(s)"to execute the test.If every thing is ok you should see the following result in the output windowIf you have ReSharper installed you can just start the test by clicking the yellow-green circle on the left border and choose Run.The result is as followsIn case of ProblemsIf your test fails double check that you find the following files in your target directory(that is: m:dev\projects\FirstSolution\src\FirstSolution.Tests\bin\debug)Double check also if you have no typos in the NHibernate configuration file(hibernate.cfg.xml)or in the mapping file(Product.hbm.xml).Finally check whether you have set the"Build Action"of the mapping file(Product.hbm.xml)to"Embedded Resource".Only continue if the test succeeds.Our first CRUD operationsNow obviously our system is ready to start.We have successfully implemented our Domain, defined the mapping files and configured NHibernate.Finally we have used NHibernate to automatically generate the database schema from our Domain(and our mapping files).In the spirit of DDD(see e.g.Domain Driven Design by Eric Evans)we define a repository for all crud operations(create,read,update and delete).The repository interface is part of the domain where as the implementation is not!The implementation is infrastructure specific.We want to keep our domain persistence ignorant(PI).Add a new interface to the domain folder of our FirstSolution project.Call it IProductRepository. Let's define the following interfaceusing System;using System.Collections.Generic;namespace FirstSolution.Domain{public interface IProductRepository{void Add(Product product);void Update(Product product);void Remove(Product product);Product GetById(Guid productId);Product GetByName(string name);ICollection<Product>GetByCategory(string category);}}Add a class ProductRepository_Fixture to the test project of the solution and add the following code[TestFixture]public class ProductRepository_Fixture{private ISessionFactory_sessionFactory;private Configuration_configuration;[TestFixtureSetUp]public void TestFixtureSetUp(){_configuration=new Configuration();_configuration.Configure();_configuration.AddAssembly(typeof(Product).Assembly);_sessionFactory=_configuration.BuildSessionFactory();}}In the fourth line of the method TestFixtureSetUp we create a session factory.This is an expensive process and should thus be executed only once.That's the reason why I put it into this method which is only executed once during a test cycle.To keep our test methods side effect free we re-create our database schema before the execution of each test method.Thus we add the following method[SetUp]public void SetupContext(){new SchemaExport(_configuration).Execute(false,true,false,false);}And now we can implement the test method to add a new product instance to the database.Startby adding a new folder called Repositories to your FirstSolution project.Add a class ProductRepository to this folder.Make the ProductRepository inherit from the interface IProductRepository.using System;using System.Collections.Generic;using FirstSolution.Domain;namespace FirstSolution.Repositories{public class ProductRepository:IProductRepository{public void Add(Product product){throw new NotImplementedException();}public void Update(Product product){throw new NotImplementedException();}public void Remove(Product product){throw new NotImplementedException();}public Product GetById(Guid productId){throw new NotImplementedException();}public Product GetByName(string name){throw new NotImplementedException();}public ICollection<Product>GetByCategory(string category){throw new NotImplementedException();}}}Manipulating DataNow go back to the ProductRepository_Fixture test class and implement the first test method[Test]public void Can_add_new_product(){var product=new Product{Name="Apple",Category="Fruits"};IProductRepository repository=new ProductRepository();repository.Add(product);}The first run of the test method will fail since we have not yet implemented the Add method in the repository class.Let's do it.But wait,we have to define a little helper class first which provides us session objects on demand.using FirstSolution.Domain;using NHibernate;using NHibernate.Cfg;namespace FirstSolution.Repositories{public class NHibernateHelper{private static ISessionFactory_sessionFactory;private static ISessionFactory SessionFactory{get{if(_sessionFactory==null){var configuration=new Configuration();configuration.Configure();configuration.AddAssembly(typeof(Product).Assembly);_sessionFactory=configuration.BuildSessionFactory();}return_sessionFactory;}}public static ISession OpenSession(){return SessionFactory.OpenSession();}}}This class creates a session factory only the first time a client needs a new session.Now we can define the Add method in the ProductRepository as followspublic void Add(Product product){using(ISession session=NHibernateHelper.OpenSession())using(ITransaction transaction=session.BeginTransaction()){session.Save(product);mit();}}The second run of the test method will again fail with the following messageThat's because NHibernate is by default configured to use lazy load for all entities.That is the recommended approach and I warmly recommend not to change it for a maximum of flexibility.How can we solve this issue?It's easy we have to just make all our properties(and methods)of the domain object(s)virtual.Let's do this for our Product classpublic class Product{public virtual Guid Id{get;set;}public virtual string Name{get;set;}public virtual string Category{get;set;}public virtual bool Discontinued{get;set;}}Now run the test again.It should succeed and we get the following outputNote the sql spit out by NHibernate.Now we think that we have successfully inserted a new product into the database.But let's test it whether it is really so.Let's extend our test method[Test]public void Can_add_new_product(){var product=new Product{Name="Apple",Category="Fruits"};IProductRepository repository=new ProductRepository();repository.Add(product);//use session to try to load the productusing(ISession session=_sessionFactory.OpenSession()){var fromDb=session.Get<Product>(product.Id);//Test that the product was successfully insertedAssert.IsNotNull(fromDb);Assert.AreNotSame(product,fromDb);Assert.AreEqual(,);Assert.AreEqual(product.Category,fromDb.Category);}}Run the test again.Hopefully it will succeed...Now we are ready to implement also the other methods of the repository.For testing this we would rather have a repository(that is database table)already containing some products.Nothing easier than this.Just add a method CreateInitialData to the test class as followsprivate readonly Product[]_products=new[]{new Product{Name="Melon",Category="Fruits"},new Product{Name="Pear",Category="Fruits"},new Product{Name="Milk",Category="Beverages"},new Product{Name="Coca Cola",Category="Beverages"},new Product{Name="Pepsi Cola",Category="Beverages"},};private void CreateInitialData(){using(ISession session=_sessionFactory.OpenSession())using(ITransaction transaction=session.BeginTransaction()){foreach(var product in_products)session.Save(product);mit();}}Call this method from the SetupContext method(after the create schema call)and we are done. Now each time after the database schema is created the database is populated with some products.Let's test the Update method of the repository with the following code[Test]public void Can_update_existing_product(){var product=_products[0];="Yellow Pear";IProductRepository repository=new ProductRepository();repository.Update(product);//use session to try to load the productusing(ISession session=_sessionFactory.OpenSession()){var fromDb=session.Get<Product>(product.Id);Assert.AreEqual(,);}}When running for the first time this code will fail since the Update method has not yet been implemented in the repository.Note:This is the expected behavior since in TDD the first time you run a test it should always fail!Analogous to the Add method we implement the Update method of the repository.The only difference is that we call the update method of the NHibernate session object instead of the save method.public void Update(Product product){using(ISession session=NHibernateHelper.OpenSession())using(ITransaction transaction=session.BeginTransaction()){session.Update(product);mit();}}Run the test again an watch it succeed.The delete method is straight forward.When testing whether the record has really been deleted we just assert that the value returned by the session's get method is equal to null.Here is the test method[Test]public void Can_remove_existing_product(){var product=_products[0];IProductRepository repository=new ProductRepository();repository.Remove(product);using(ISession session=_sessionFactory.OpenSession()){var fromDb=session.Get<Product>(product.Id);Assert.IsNull(fromDb);}}and here the implementation of the Remove method in the repositorypublic void Remove(Product product){using(ISession session=NHibernateHelper.OpenSession())using(ITransaction transaction=session.BeginTransaction()){session.Delete(product);mit();}}Querying the DatabaseWe still have to implement the three methods which query the database for objects.Let's start with the most easy one,the GetById.First we write the test[Test]public void Can_get_existing_product_by_id(){IProductRepository repository=new ProductRepository();var fromDb=repository.GetById(_products[1].Id);Assert.IsNotNull(fromDb);Assert.AreNotSame(_products[1],fromDb);Assert.AreEqual(_products[1].Name,);}and then the code to fulfill the testpublic Product GetById(Guid productId){using(ISession session=NHibernateHelper.OpenSession())return session.Get<Product>(productId);}Now that was easy.For the following two methods we use a new method of the session object. Let's start with the GetByName method.As usual we write the test first[Test]public void Can_get_existing_product_by_name(){IProductRepository repository=new ProductRepository();var fromDb=repository.GetByName(_products[1].Name);Assert.IsNotNull(fromDb);Assert.AreNotSame(_products[1],fromDb);Assert.AreEqual(_products[1].Id,fromDb.Id);}The implementation of the GetByName method can be done by using two different approaches. The first is using HQL(Hibernate Query Language)and the second one HCQ(Hibernate Criteria Query).Let's start with HQL.HQL is a object oriented query language similar(but not equal to) SQL.To be added:implemetation of GetByName using HQL.Implement HCQ as below this works asexpected and returns a product entity.In the above sample I have introduced a commonly used technique when using NHibernate.It's called fluent interfaces.As a result the code is less verbose and easier to understand.You can see that a HQL query is a string which can have embedded(named)parameters.Parameters are prefixed by a':'.NHibernate defines many helper methods(like SetString used in the example)to assign values of various types to those parameters.Finally by using UniqueResult I tell NHibernate that I expect only one record to return.If more than one record is returned by the HQL query then an exception is raised.To get more information about HQL please read the online documentation.The second version uses a criteria query to search the requested product.You need to add a reference to NHibernate.Criterion on your repository page.public Product GetByName(string name){using(ISession session=NHibernateHelper.OpenSession()){Product product=session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Name",name)).UniqueResult<Product>();return product;}}Many users of NHibernate think that this approach is more object oriented.On the other hand a complex query written with criteria syntax can quickly become difficult to understand.The last method to implement is GetByCategory.This method returns a list of products.The test can be implemented as follows[Test]public void Can_get_existing_products_by_category(){IProductRepository repository=new ProductRepository();var fromDb=repository.GetByCategory("Fruits");Assert.AreEqual(2,fromDb.Count);Assert.IsTrue(IsInCollection(_products[0],fromDb));Assert.IsTrue(IsInCollection(_products[1],fromDb));}private bool IsInCollection(Product product,ICollection<Product>fromDb){foreach(var item in fromDb)if(product.Id==item.Id)return true;return false;}and the method itself might contain the following codepublic ICollection<Product>GetByCategory(string category){using(ISession session=NHibernateHelper.OpenSession()){var products=session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Category",category)).List<Product>();return products;}}SummaryIn this article I have shown you how to implement a basic sample domain,define the mapping to a database and how to configure NHibernate to be able to persist domain objects in the database.I have shown you how to typically write and test CRUD methods for your domain objects.I have taken MS SQL Compact Edition as sample database but any other supported database can be used (you only have to change the hibernate.cfg.xml file accordingly).Ee have no dependencies on external frameworks or tools other than the database and NHibernate itself(.NET of course never counts here).。

一个简单的Hibernate登录实例

一个简单的Hibernate登录实例

这是一个关于Hibernate登录的实例,开发工具:MyEclipse2014,mysql,jdk,hibernate, struts2。

下面是实例的具体步骤。

1.新建一个Web Project项目Hibernate_EXA。

2.在mysql数据库中新建数据库名为stms和表user,user两个字段name和password,均设为varchar型,name为主键。

3.打开数据库试图,新建一个数据库连接,具体步骤略,可以参考之前的博客地址:/moon__stone888888/article/details/5178 2390数据连接名命名为MySqlConn,这个由自己定义。

4.在项目中配置hibernate,可以参考之前的博客地址:/moon__stone888888/article/details/5177 9256在配置向导中的数据库驱动(DB Driver)选择MySqlConn,按向导配置直到完成。

5.使用Hibernate自动生成永久的java文件在src目录下新建bean包。

在DB Browser下,右键stms数据库下的user 表,选择Hibernate Reverse Engineering,弹出如下对话框:如上图所示,点击“Next >”,如下图如上图所示,点击“Next >”,如下图如上图,点击“Finish”,完成配置后,在bean包下面生成了三个文件,AbstractUser.java,User.jva,User.hbm.xml。

同时可以看到hibernate.cfg.xml文件里有了User.hbm.xml的映射。

<?xml version='1.0'encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.url">jdbc:mysql://localhost:3306/stms</property><property name="ername">root</property><property name="connection.password">cyj</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="myeclipse.connection.profile">MySqlConn</property><mapping resource="bean/User.hbm.xml"/></session-factory></hibernate-configuration>6.添加struts2框架,具体步骤省略,可以参考之前的博客地址:/moon__stone888888/article/deta ils/518039977.新建一个包com.su,新建一个login.java类,放到com.su下,longin.java文件内容为:import java.util.*;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import bean.Good;import er;public class login {private String username;private String password;public String getUsername() {return username;}public void setUsername(String userName) {ername = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String execute() {/*if("suo".equals(erName) && "123".equals(this.password)) return "success";elsereturn "fail";*/boolean has = false;try {SessionFactory sf = newConfiguration().configure().buildSessionFactory();Session session = sf.openSession();List catlist = null;catlist = session.createQuery("from User").list();Transaction tx = session.beginTransaction();if (catlist != null) {Iterator it = catlist.iterator();while (it.hasNext()) {User user = (User) it.next();//System.out.println("ID: " + good.getId() + " 性别:"//+ good.getName()+"\n");if(user.getName().equals(ername) &&user.getPassword().equals(this.password)) {has = true;break;}elsehas = false;}}mit();session.clear();if (has)return"success";elsereturn"fail";}catch (HibernateException e) {// TODO: handle exceptione.printStackTrace();return"fail";}}}Struts.xml的配置为:<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""/dtds/struts-2.1.dtd"> <struts><package name="test"namespace="/test"extends="struts-default"> <action name="login"class="com.su.login"method="execute"> <result name="success">/WEB-INF/result/success.jsp</result><result name="fail">/WEB-INF/result/fail.jsp</result> </action></package></struts>Web.xml的配置为:<?xml version="1.0"encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance"xmlns="/xml/ns/javaee"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1"><display-name>Hibernate_EXA</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecu teFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>index.jsp的文件内容为:<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort ()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>用户登录界面</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><script type="text/javascript">// 验证输入不为空的脚本代码function checkForm(form){if (ername.value == ""){alert("用户名不能为空!");ername.focus();return false;}if (form.password.value == ""){alert("密码不能为空!");form.password.focus();return false;}return true;}</script><body><%=request.getContextPath() %> <br/><%=basePath %> <br/><form action="/Hibernate_EXA/test/login" method="post" onSubmit="return checkForm(this);">用户名:<input type="text" name="username"/><br/>密码:<input type="password" name="password"/><br/><input type="submit" value="登录"><input type="reset" value="重置"></form></body></html>启动tomcat服务器,可以进行登录测试了。

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

NHibernate相信大家都已非常熟悉,园子里有很多高手写了相关的系列文章,不过我还是NHibernate的一名初学者,在此将一个晚上学习成果分享一下,一个很简单的利用NHibernate实现增删改的例子。

本例中使用的NHibernate版本为版本为官方2008年9月29日最新发布的NHibernate-2.0.1.GA 版本,点击下载1 首先创建一个数据库NHibernateSample,使用的数据库版本为sqlserver2005。

在该数据库中创建表UserInfo。

CREATE TABLE[dbo].[UserInfo]([UserInfoID][int]IDENTITY(1,1) NOT NULL,[UserName][varchar](20) COLLATE Chinese_PRC_CI_AS NULL,[Email][varchar](100) COLLATE Chinese_PRC_CI_AS NULL)2 打开vs2008,创建web application 命名为Web,解决方案的名称设为NHibernateDemo,然后在此解决方案下添加两个类库项目BLL和Model。

3 解压下载的NHibernate包,将NHibernate-2.0.1.GA-bin\bin\net-2.0目录下的dll文件复制到web项目中的DLL文件夹中。

DLL文件夹用来存放一些公用的dll文件。

4 在Model项目中创建两个目录:Entities和Mappings。

分别存放实体类和映射文件。

在Entities目录下创建类UserInfo.cspublic class UserInfo{public virtual int UserInfoID { get; set; }public virtual string UserName { get; set; }public virtual string Email { get; set; }}需要注意到是实体类中的属性必须加virtual修饰符。

在Mappings目录下创建映射文件UserInfo.hbm.xml<?xml version="1.0" encoding="utf-8" ?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"assembly="Model" namespace="Model"><class name ="erInfo,Model" table="UserInfo"> <id name="UserInfoID" column="UserInfoID" type="Int32" unsave d-value="0"><generator class ="native"></generator></id><property name="UserName" column ="UserName" type="string" le ngth="20" not-null="false"/><property name="Email" column="Email" type="string" length="1 00" not-null="false"></property></class></hibernate-mapping>映射文件创建好后,要修改该文件的输入操作为“嵌入式资源”,默认情况下为内容,在映射文件上右击属性,修改如下:5 在BLL项目中创建类UserInfoBLL.cs 用来实现对UserInfo表的增删改操作。

在BLL项目中添加对Model和NHibernate的引用UserInfoBLL.csl类的代码如下:public class UserInfoBLL{private string path = HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml");public bool Insert(UserInfo userInfo){Configuration cfg = new Configuration().Configure(path);ISession session = cfg.BuildSessionFactory().OpenSession();ITransaction transaction = session.BeginTransaction();try{session.Save(userInfo);mit();return true;}catch (Exception e){transaction.Rollback();return false;}finally{session.Close();}}public IList<UserInfo> GetUsers(){Configuration cfg = new Configuration().Configure(path);ISession session = cfg.BuildSessionFactory().OpenSession();//使用HQLIList<UserInfo> list = session.CreateQuery(" from UserI nfo").List<UserInfo>();return list;}public bool Update(UserInfo userInfo){Configuration cfg = new Configuration().Configure(path);ISession session = cfg.BuildSessionFactory().OpenSession();ITransaction transaction = session.BeginTransaction();try{session.Update(userInfo);mit();return true;}catch (Exception e){transaction.Rollback();return false;}finally{session.Close();}}public bool Delete(UserInfo userInfo){Configuration cfg = new Configuration().Configure(path);ISession session = cfg.BuildSessionFactory().OpenSession();ITransaction transaction = session.BeginTransaction();try{session.Delete(userInfo);mit();return true;}catch (Exception e){transaction.Rollback();return false;}finally{session.Close();}}public UserInfo GetUserInfoById(int userId){Configuration cfg = new Configuration().Configure(path);ISession session = cfg.BuildSessionFactory().OpenSession();return session.Get<UserInfo>(userId);}}上面的GetUsers方法中用的是HQL查询的数据,NHibernate查询数据的方式有三种,具体参见NHibernate文档。

5 在web项目的根目录下添加hibernate.cfg.xml文件,该文件用于配置一些数据库连接方面的信息。

<?xml version="1.0" encoding="utf-8"?><hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory name="NHibernateDemo"><property name="connection.driver_class">NHibernate.Driver.Sq lClientDriver</property><property name="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=NHibernateSample; Integrated Security=True;Pooling=False;uid=sa;pwd=sa123 </property><property name="adonet.batch_size">10</property><property name="show_sql">false</property><property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property><property name="use_outer_join">true</property><property name="command_timeout">10</property><property name="query.substitutions">true 1, false 0, yes 'Y ', no 'N'</property><mapping assembly="Model"/></session-factory></hibernate-configuration>6 在web项目中添加Model和BLL的引用。

相关文档
最新文档