DAO层注入HibernateTemplate的两种方式

本文介绍两种在DAO层注入HibernateTemplate的方式:一是普通方式,通过setter注入;二是使用继承HibernateDaoSupport类的方法,直接获取HibernateTemplate实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-------------------------siwuxie095

  

  

  

  

  

  

  

  

  

  

DAO 层注入 HibernateTemplate 的两种方式

  

  

方式一:普通方式

  

  

具体实现如下:

  

1)编写页面

  

add.jsp:

  

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>添加用户</title>

</head>

<body>

 

<formaction="${pageContext.request.contextPath }/user_add.action"method="post">

用户名:<inputtype="text"name="username"/>

地址:<inputtype="text"name="address"/>

<inputtype="submit"name="提交"/>

</form>

 

</body>

</html>

  

  

  

succ.jsp:

  

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>添加成功</title>

</head>

<body>

 

<h1>添加成功!<ahref="${pageContext.request.contextPath }/add.jsp">继续添加</a></h1>

 

</body>

</html>

  

  

  

2)编写实体类

  

User.java:

  

package com.siwuxie095.entity;

  

public class User {

 

Integer uid;

String username;

String address;

 

public Integer getUid() {

return uid;

}

publicvoid setUid(Integer uid) {

this.uid = uid;

}

 

public String getUsername() {

return username;

}

publicvoid setUsername(String username) {

this.username = username;

}

 

public String getAddress() {

return address;

}

publicvoid setAddress(String address) {

this.address = address;

}

 

@Override

public String toString() {

return"User [uid=" + uid + ", username=" + username +

", address=" + address + "]";

}

 

}

  

  

  

3)在Hibernate 映射配置文件中进行配置

  

User.hbm.xml:

  

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

<hibernate-mapping>

  

<classname="com.siwuxie095.entity.User"table="t_user">

 

<idname="uid"column="uid">

<generatorclass="native"></generator>

</id>

 

<propertyname="username"column="username"></property>

<propertyname="address"column="address"></property>

 

</class>

 

</hibernate-mapping>

  

  

  

4)在Hibernate 核心配置文件中进行配置

  

hibernate.cfg.xml:

  

<?xmlversion="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>

 

 

<propertyname="hibernate.show_sql">true</property>

<propertyname="hibernate.format_sql">true</property>

<!-- 注意:只有配置 hibernate.hbm2ddl.auto update,才能自动创建表 -->

<propertyname="hibernate.hbm2ddl.auto">update</property>

<propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!--

原来的配置:

<property name="hibernate.current_session_context_class">thread</property>

 

SSH 框架整合中会报错,要么将这个配置删了,要么改成如下配置

 

参考链接:http://blog.youkuaiyun.com/maoyuanming0806/article/details/61417995

-->

<propertyname="hibernate.current_session_context_class">

org.springframework.orm.hibernate5.SpringSessionContext

</property>

 

 

<mappingresource="com/siwuxie095/entity/User.hbm.xml"/>

 

</session-factory>

</hibernate-configuration>

  

  

  

5)编写Action 类

  

package com.siwuxie095.action;

  

import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.siwuxie095.entity.User;

import com.siwuxie095.service.UserService;

  

public class UserAction extends ActionSupport implements ModelDriven<User> {

  

private User user=new User();

 

@Override

public User getModel() {

return user;

}

 

private UserService userService;

 

publicvoid setUserService(UserService userService) {

this.userService = userService;

}

 

public String add() {

userService.add(user);

return"add";

}

  

}

  

  

  

6)编写Service 类

  

UserService.java:

  

package com.siwuxie095.service;

  

import org.springframework.transaction.annotation.Transactional;

  

import com.siwuxie095.dao.UserDao;

import com.siwuxie095.entity.User;

  

@Transactional

public class UserService {

 

private UserDao userDao;

 

publicvoid setUserDao(UserDao userDao) {

this.userDao = userDao;

}

  

publicvoid add(User user) {

userDao.add(user);

}

 

}

  

  

  

7)编写DAO 接口及其实现类

  

UserDao.java:

  

package com.siwuxie095.dao;

  

import com.siwuxie095.entity.User;

  

public interface UserDao {

  

void add(User user);

 

}

  

  

  

UserDaoImpl.java:

  

package com.siwuxie095.dao.impl;

  

import org.springframework.orm.hibernate5.HibernateTemplate;

  

import com.siwuxie095.dao.UserDao;

import com.siwuxie095.entity.User;

  

public class UserDaoImpl implements UserDao {

 

private HibernateTemplate hibernateTemplate;

 

publicvoid setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

  

@Override

publicvoid add(User user) {

hibernateTemplate.save(user);

}

  

}

  

  

  

8)在Struts2 核心配置文件中进行配置

  

struts.xml:

  

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

"http://struts.apache.org/dtds/struts-2.3.dtd">

  

<struts>

 

<packagename="demo"extends="struts-default"namespace="/">

 

<actionname="user_*"class="userAction"method="{1}">

<resultname="add">/succ.jsp</result>

</action>

 

</package>

  

</struts>

  

  

  

9)在Spring 核心配置文件中进行配置

  

applicationContext.xml:

  

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd">

 

 

<!-- (1) -->

<!-- 配置 C3P0 连接池 -->

<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

<propertyname="driverClass"value="com.mysql.jdbc.Driver"/>

<!--

jdbc:mysql:///test_db jdbc:mysql://localhost:3306/test_db 的简写

-->

<propertyname="jdbcUrl"value="jdbc:mysql:///test_db"/>

<propertyname="user"value="root"/>

<propertyname="password"value="8888"/>

</bean>

 

 

<!-- SessionFactory 对象的创建交给 Spring 进行管理 -->

<beanid="sessionFactory"

class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

<!--

因为在 Hibernate 核心配置文件中,没有数据库配置,

而是在 Spring 的核心配置文件中进行配置,所以需要

注入 dataSource

LocalSessionFactoryBean 中有相关属性,所以可以

注入

-->

<propertyname="dataSource"ref="dataSource"></property>

<!-- 指定 Hibernate 核心配置文件的位置 -->

<propertyname="configLocations"value="classpath:hibernate.cfg.xml"></property>

</bean>

 

 

 

<!-- (2) -->

<!-- 配置 Action 对象 -->

<beanid="userAction"class="com.siwuxie095.action.UserAction" scope="prototype">

<propertyname="userService"ref="userService"></property>

</bean>

  

<!-- 配置 Service 对象 -->

<beanid="userService"class="com.siwuxie095.service.UserService">

<propertyname="userDao"ref="userDaoImpl"></property>

</bean>

  

<!-- 配置 Dao 实现类对象 -->

<beanid="userDaoImpl"class="com.siwuxie095.dao.impl.UserDaoImpl">

<propertyname="hibernateTemplate"ref="hibernateTemplate"></property>

</bean>

  

<!-- 配置 HibernateTemplate 对象 -->

<beanid="hibernateTemplate"class="org.springframework.orm.hibernate5.HibernateTemplate">

<!-- 注入 SessionFactory 对象 -->

<propertyname="sessionFactory"ref="sessionFactory"></property>

</bean>

 

 

 

<!-- (3) -->

<!-- 配置事务管理器 HibernateTransactionManager -->

<beanid="transactionManager"

class="org.springframework.orm.hibernate5.HibernateTransactionManager">

<!--注入 SessionFactory 对象 -->

<propertyname="sessionFactory"ref="sessionFactory"></property>

</bean>

 

<!-- 开启事务注解 -->

<tx:annotation-driventransaction-manager="transactionManager"/>

 

 

</beans>

  

  

  

10)在部署描述文件中进行配置

  

web.xml:

  

<?xmlversion="1.0"encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1">

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

 

<!-- 配置 Struts2 的核心过滤器 -->

<filter>

<filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

</filter>

 

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

 

<!-- 配置 Spring 的监听器 ContextLoaderListener -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 

<!-- 配置 Spring 核心配置文件的位置(路径) -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

 

</web-app>

  

  

  

11)访问路径

  

http://localhost:8080/工程名/add.jsp

  

  

  

  

  

  

  

方式二:让DAO 接口实现类继承 HibernateDaoSupport 类

  

  

「只有DAO 接口实现类和 Spring 核心配置文件与方式一不同,其它同上」

  

  

具体实现如下:

  

1)重写DAO 接口实现类

  

UserDaoImpl.java:

  

package com.siwuxie095.dao.impl;

  

import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

  

import com.siwuxie095.dao.UserDao;

import com.siwuxie095.entity.User;

  

/**

* DAO 接口实现类继承 HibernateDaoSupport 类,直接获取 HibernateTemplate

*/

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

 

@Override

publicvoid add(User user) {

 

// 直接通过 this 获取 HibernateTemplate,调用 save() 方法保存

this.getHibernateTemplate().save(user);

 

/*

* 此时,也可以获取 SessionFactory

*

* 法一:this.getSessionFactory()

* 法二:this.getHibernateTemplate().getSessionFactory()

*

*

* 此时,也可以获取 Session

*

* 法一:this.getSessionFactory().getCurrentSession()

* 法二:...

*/

}

 

}

  

  

  

2)重写Spring 核心配置文件

  

applicationContext.xml:

  

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd">

 

 

<!-- (1) -->

<!-- 配置 C3P0 连接池 -->

<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

<propertyname="driverClass"value="com.mysql.jdbc.Driver"/>

<!--

jdbc:mysql:///test_db jdbc:mysql://localhost:3306/test_db 的简写

-->

<propertyname="jdbcUrl"value="jdbc:mysql:///test_db"/>

<propertyname="user"value="root"/>

<propertyname="password"value="8888"/>

</bean>

 

 

<!-- SessionFactory 对象的创建交给 Spring 进行管理 -->

<beanid="sessionFactory"

class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

<!--

因为在 Hibernate 核心配置文件中,没有数据库配置,

而是在 Spring 的核心配置文件中进行配置,所以需要

注入 dataSource

LocalSessionFactoryBean 中有相关属性,所以可以

注入

-->

<propertyname="dataSource"ref="dataSource"></property>

<!-- 指定 Hibernate 核心配置文件的位置 -->

<propertyname="configLocations"value="classpath:hibernate.cfg.xml"></property>

</bean>

 

 

 

<!-- (2) -->

<!-- 配置 Action 对象 -->

<beanid="userAction"class="com.siwuxie095.action.UserAction" scope="prototype">

<propertyname="userService"ref="userService"></property>

</bean>

  

<!-- 配置 Service 对象 -->

<beanid="userService"class="com.siwuxie095.service.UserService">

<propertyname="userDao"ref="userDaoImpl"></property>

</bean>

  

<!-- 配置 Dao 实现类对象 -->

<beanid="userDaoImpl"class="com.siwuxie095.dao.impl.UserDaoImpl">

<!--

注入 SessionFactory 对象

 

此时,这里不再注入 HibernateTemplate,由于 UserDaoImpl 继承了

HibernateDaoSupport,直接注入 SessionFactory 对象,就能获得

HibernateTemplate 对象

-->

<propertyname="sessionFactory"ref="sessionFactory"></property>

</bean>

  

 

 

<!-- (3) -->

<!-- 配置事务管理器 HibernateTransactionManager -->

<beanid="transactionManager"

class="org.springframework.orm.hibernate5.HibernateTransactionManager">

<!--注入 SessionFactory 对象 -->

<propertyname="sessionFactory"ref="sessionFactory"></property>

</bean>

 

<!-- 开启事务注解 -->

<tx:annotation-driventransaction-manager="transactionManager"/>

 

 

</beans>

  

  

  

  

  

  

  

  

  

  

  

【made by siwuxie095】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值