HibernateTemplate实现CRUD操作

2024-01-03 01:38

本文主要是介绍HibernateTemplate实现CRUD操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

  

  

  

  

  

  

  

  

HibernateTemplate 实现 CRUD 操作

  

  

1、在SSH 框架中使用HibernateTemplate 模板类实现CRUD 操作

  

  

  

2、HibernateTemplate 是 Spring 对 Hibernate 的封装

  

  

  

3、使用HibernateTemplate 时,必须进行事务管理,否则将报错

  

建议:使用基于注解方式的声明式事务管理

  

  

  

4、测试

  

1)编写一个实体类

  

User.java:

  

package com.siwuxie095.entity;

  

public class User {

  

private Integer uid;

private String username;

private 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 +"]";

}

 

}

  

  

  

2)编写一个Action 类

  

UserAction.java:

  

package com.siwuxie095.action;

  

import com.opensymphony.xwork2.ActionSupport;

import com.siwuxie095.service.UserService;

  

public class UserActionextends ActionSupport {

 

private UserService userService;

 

publicvoid setUserService(UserService userService) {

this.userService = userService;

}

  

 

@Override

public String execute()throws Exception {

 

//userService.add();

userService.find();

 

return"none";

}

 

}

  

  

  

3)编写一个Service 类

  

UserService.java:

  

package com.siwuxie095.service;

  

import org.springframework.transaction.annotation.Transactional;

  

import com.siwuxie095.dao.UserDao;

  

/**

* Service层进行声明式事务管理

*加上注解 @Transactional

*

*使用 HibernateTemplate实现 CRUD操作,

*一定要加上事务管理,否则将报错

*/

@Transactional

public class UserService {

 

private UserDao userDao;

 

publicvoid setUserDao(UserDao userDao) {

this.userDao = userDao;

}

 

publicvoid add() {

userDao.add();

}

 

publicvoid find() {

userDao.find();

}

 

}

  

  

  

4)编写一个Dao 接口和其实现类:

  

UserDao.java:

  

package com.siwuxie095.dao;

  

public interface UserDao {

 

publicvoid add();

publicvoid find();

 

}

  

  

  

UserDaoImpl.java:

  

package com.siwuxie095.dao.impl;

  

import java.util.List;

  

import org.springframework.orm.hibernate5.HibernateTemplate;

  

import com.siwuxie095.dao.UserDao;

import com.siwuxie095.entity.User;

  

public class UserDaoImplimplements UserDao {

 

private HibernateTemplate hibernateTemplate;

 

publicvoid setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

 

 

@Override

publicvoid add() {

User user=new User();

user.setUsername("小白");

user.setAddress("中国");

hibernateTemplate.save(user);

 

/*

* HibernateTemplate还有 update()delete()方法,

*都是直接传入对象即可

*/

}

  

  

@Override

publicvoid find() {

 

//根据 id查询

User user=hibernateTemplate.get(User.class,1);

System.out.println(user);

System.out.println("------------------");

 

//查询所有

List<User> list=(List<User>) hibernateTemplate.find("from User");

 

for (User user1 : list) {

System.out.println(user1);

}

 

System.out.println("------------------");

 

//根据条件查询

List<User> listx=(List<User>) hibernateTemplate.find("from User where username=?","小黑");

 

for (User user2 : listx) {

System.out.println(user2);

}

 

/*

* HibernateTemplate findByCriteria()方法可以做到分页查询

*

* find()方法则无法做到

*/

 

}

  

}

  

  

  

5)在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>

  

  

  

6)在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.csdn.net/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>

  

  

  

7)在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>

  

  

  

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="/">

 

<!--

此时,class属性对应 Spring核心配置文件中 Bean id

 

如果还写 Action类的全限定名,Action对象就会创建两次

-->

<actionname="user"class="userAction"></action>

 

</package>

  

</struts>

  

  

  

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

  

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/javaeehttp://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>

 

 

<filter>

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

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

  

  

  

10)访问路径

  

http://localhost:8080/工程名/user.action

  

  

  

  

  

  

  

  

  

【made by siwuxie095】

这篇关于HibernateTemplate实现CRUD操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/564223

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal