在Java Web程序中使用Hibernate
在Java Web程序中使用Hibernate与普通Java程序一样。本文中将使用Servlet和JSP结合Hibernate实现数据库表的增删改查操作。
Web程序中,hibernate.cfg.xml中必须配置current_session_context_class参数。如果使用JBoss等内置Hibernae的容器,参数值要配置为jta,其他容器(如Tomcat等)需要配置为thread。
1. 创建工程并搭建Hibernate框架
在MyEclipse中创建一个Web工程,工程名为hibernate_web,把MySQL数据库驱动包和JSTL需要的jar包复制到WebRoot/WEB-INF/lib目录下;然后使用MyEclipse向导把Hibernate的jar包导到工程中。关于搭建Hibernate框架,可以参考网上的教程,这里就不再介绍了。接着,使用Hibernate连接数据库,并通过数据库表自动生成数据库对应的实体类和实体类映射文件。所使用的数据库表是MySQL的bank数据库中的users表。
自动生成及修改的代码如下:
package com.cn.vo; /**
* UsersVo entity. @author MyEclipse Persistence Tools
*/ public class UsersVo implements java.io.Serializable { // Fields private Integer id;
private String name;
private Integer age;
private String tel;
private String address; // Constructors /** default constructor */
public UsersVo() {
} /** minimal constructor */
public UsersVo(Integer id) {
this.id = id;
} /** full constructor */
public UsersVo(Integer id, String name, Integer age, String tel,
String address) {
this.id = id;
this.name = name;
this.age = age;
this.tel = tel;
this.address = address;
} // Property accessors public Integer getId() {
return this.id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return this.age;
} public void setAge(Integer age) {
this.age = age;
} public String getTel() {
return this.tel;
} public void setTel(String tel) {
this.tel = tel;
} public String getAddress() {
return this.address;
} public void setAddress(String address) {
this.address = address;
} }
UsersVo.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.cn.vo.UsersVo" table="users" catalog="bank">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
<property name="age" type="java.lang.Integer">
<column name="age" />
</property>
<property name="tel" type="java.lang.String">
<column name="tel" length="20" />
</property>
<property name="address" type="java.lang.String">
<column name="address" length="50" />
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml(修改)
<?xml version='1.0' encoding='gbk'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<!-- 声明使用SQL语句是MySQL数据库的SQL语句(MySQL方言) -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property> <!-- 在控制台打印执行的SQL语句 -->
<property name="show_sql">true</property> <!-- 指定Hibernate启动的时候自动更新表,如果不存在则创建 -->
<property name="hbm2ddl.auto">update</property> <!-- 使用线程,防止遇到异常 -->
<property name="current_session_context_class">thread</property> <!-- JDBC配置代码包括数据库驱动、用户名密码及连接地址 -->
<property name="connection.url">
jdbc:mysql://localhost:3306/bank
</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">
com.mysql.jdbc.Driver
</property> <!-- 指定Hibernate的映射文件 -->
<mapping resource="com/cn/vo/UsersVo.hbm.xml" /> </session-factory> </hibernate-configuration>
HibernateSessionFactory.java
package com.cn.hibernate; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration; /**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
} /**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }
2. 编写数据持久层
为了使程序结构清晰,数据持久层独立出来,放在DAO层中,在DAO层的类中编写数据的增删修改查方法,通过这些方法操作数据。在使用时,只需要根据实际情况来调用DAO层中的方法就可以了。这个例子中,DAO层只有一个类,类名为HibernateDao,HibernateDao类的代码如下:
package com.cn.dao; import org.hibernate.HibernateException;
import org.hibernate.Session; import java.util.List; import com.cn.hibernate.HibernateSessionFactory;
import com.cn.vo.UsersVo; public class HibernateDao {
//添加数据的方法
public void add(UsersVo usersVo){
//调用HibernateSessionFactory的会话
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction(); //开启事务
session.persist(usersVo); //将对象添加到数据库
session.getTransaction().commit(); //提交事务 } catch (Exception e) {
session.getTransaction().rollback(); //回滚事务
} finally {
session.close(); //关闭session
}
} //修改数据的方法
public void modifyUsers(UsersVo usersVo){
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction(); //开启事务
session.update(usersVo); //修改数据
session.getTransaction().commit(); //提交事务
} catch (Exception e) {
session.getTransaction().rollback(); //回滚事务
} finally {
session.close(); //关闭session
}
} //从表中删除数据
public void delete(int id){
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
UsersVo users = (UsersVo)session.get(UsersVo.class, id);
session.delete(users);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.close();
}
} //根据id查找数据
@SuppressWarnings("unchecked")
public UsersVo queryUsersById(int id){
Session session = HibernateSessionFactory.getSession();
UsersVo users = (UsersVo)session.get(UsersVo.class, id);
return users;
} //查找多条数据
@SuppressWarnings("unchecked")
public List<UsersVo> showlist(String hql){
Session session = HibernateSessionFactory.getSession();
try {
session.beginTransaction();
return session.createQuery(hql).list(); //使用HQL查询结果,返回List对象
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.getTransaction().commit();
session.close();
}
return null;
}
}
该类中接受UsersVo类,Hibernate能够判断实体类的类型,决定操作哪个数据表。HibernateDao封装了最基本的CURD操作。
在Java Web程序中使用Hibernate的更多相关文章
- 在Java Web程序中使用监听器可以通过以下两种方法
之前学习了很多涉及servlet的内容,本小结我们说一下监听器,说起监听器,编过桌面程序和手机App的都不陌生,常见的套路都是拖一个控件,然后给它绑定一个监听器,即可以对该对象的事件进行监听以便发生响 ...
- java web程序中项目名的更改(http://localhost:8080/)后面的名字
在MyEclipse中的Web项目,如果想另换名称(Context-root)进行发布,可以在项目的属性中进行设置.设置路径如下: 右击项目XX(或选中项目XX,按快捷键Alt+Enter), 打开项 ...
- 在Java Web项目中添加定时任务
在Java Web程序中加入定时任务,这里介绍两种方式:1.使用监听器注入:2.使用Spring注解@Scheduled注入. 推荐使用第二种形式. 一.使用监听器注入 ①:创建监听器类: impor ...
- 那个执事,争先:我如何于 2015 年在 Java Web 项目中推动 HTTP/2
2015 年 5 月,HTTP/2 发布. 2015 年第 3 季度,我所在企业的一个战略级客户(而且是第二大客户)说,他们需要在当年年底之前支持 HTTP/2(原因忘了,且与本文无关,从略). 而在 ...
- (转)Java web 项目中文件路径
文件路径分为绝对路径和相对路径,在项目中页面跳转.配置文件读写.文件上传下载等等许多地方都涉及到文件路径问题. 一篇好文转载于此:http://blog.csdn.net/shendl/archive ...
- JAVA WEB项目中各种路径的获取
JAVA WEB项目中各种路径的获取 标签: java webpath文件路径 2014-02-14 15:04 1746人阅读 评论(0) 收藏 举报 分类: JAVA开发(41) 1.可以在s ...
- Java Web开发中MVC设计模式简介
一.有关Java Web与MVC设计模式 学习过基本Java Web开发的人都已经了解了如何编写基本的Servlet,如何编写jsp及如何更新浏览器中显示的内容.但是我们之前自己编写的应用一般存在无条 ...
- Java Web程序工作原理
Web开发的最重要的基本功能是HTTP:Java Web开发的最重要的基本功是Servlet Specification.HTTP和Servlet Specitication对于Web Server和 ...
- 对Java Web项目中路径的理解
第一个:文件分隔符 坑比Window.window分隔符 用\;unix采用/.于是用File.separator来跨平台 请注意:这是文件路径.在File f = new File(“c:\\hah ...
随机推荐
- Django实战(17):ajax !
现在让我们来通过ajax请求后台服务.当然首选要实现后台服务.关于“加入购物车”,我们需要的服务是这样定义的: url: http://localhost:8000/depotapp/API/c ...
- Kylin启动时错误:Failed to find metadata store by url: kylin_metadata@hbase 解决办法
一.问题背景 安装kylin后使用命令 $ kylin.sh start 后出现Failed to find metadata store by url: kylin_metadata@hbase的错 ...
- HTML Input 表单校验之datatype
凡要验证格式的元素均需绑定datatype属性,datatype可选值内置有10类,用来指定不同的验证格式. 如果还不能满足您的验证需求,可以传入自定义datatype,自定义datatype是一个非 ...
- 利用过滤器对string类型的入参进行统一trim
背景 最近做的一些项目都是后台管理系统,主要是对表单数据的增删改查操作,其中有些表单项是字符串类型的,对于这些类型的表单项就需要在保存或编辑之前要进行.trim()处理,刚开始感觉没什么,遇到了就手动 ...
- TCP 建立连接为什么要握 3 次手?
上次已经说过,没有协议,不成方圆,计算机之间的通信更是依赖于协议.今天就重点分析一下 TCP 协议. 传输控制协议 TCP 是一种面向连接的.可靠的.基于字节流的传输层通信协议,由IETF的RFC 7 ...
- Xamarin 2017.10.9更新
Xamarin 2017.10.9更新 本次更新主要解决了一些bug.Visual Studio 2017升级到15.4获得新功能.Visual Studio 2015需要工具-选项-Xamarin ...
- Python 随机数函数
random.random random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0 描述 random() 方法返回随机生成的一个实数,它在[0,1)范围 ...
- android 视频
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha 第一套完整版: 第二套完整版: 第三套完整版: 第四套完整版: 第五套完整版: ==== ...
- JMS开发指南
1.JMS消息的异步与同步接收 消息的异步接收: 异步接收是指当消息到达时,主动通知客户端,即当消息到达时转发到客户端.JMS客户端可以通过注册一个实现MessageListener接口的对象到Mes ...
- BZOJ2055 80人环游世界 网络流 费用流 有源汇有上下界的费用流
https://darkbzoj.cf/problem/2055 https://blog.csdn.net/Clove_unique/article/details/54864211 ←对有上下界费 ...