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

}

public void setUid(Integer uid) {

this.uid = uid;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getAddress() {

return address;

}

public void 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 UserAction extends ActionSupport {

private UserService userService;

public void 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;

public void setUserDao(UserDao userDao) {

this.userDao = userDao;

}

public void add() {

userDao.add();

}

public void find() {

userDao.find();

}

}

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

UserDao.java:

package com.siwuxie095.dao;

public interface UserDao {

public void add();

public void 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 UserDaoImpl implements UserDao {

private HibernateTemplate hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

@Override

public void add() {

User user=new User();

user.setUsername("小白");

user.setAddress("中国");

hibernateTemplate.save(user);

/*

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

* 都是直接传入对象即可

*/

}

@Override

public void 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:

<?xml version="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>

<class name="com.siwuxie095.entity.User" table="t_user">

<id name="uid" column="uid">

<generator class="native"></generator>

</id>

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

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

</class>

</hibernate-mapping>

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

hibernate.cfg.xml:

<?xml version="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>

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

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

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

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

<property name="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

-->

<property name="hibernate.current_session_context_class">

org.springframework.orm.hibernate5.SpringSessionContext

</property>

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

</session-factory>

</hibernate-configuration>

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

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="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 连接池 -->

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

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

<!--

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

-->

<property name="jdbcUrl" value="jdbc:mysql:///test_db"/>

<property name="user" value="root"/>

<property name="password" value="8888"/>

</bean>

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

<bean id="sessionFactory"

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

<!--

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

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

注入 dataSource

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

注入

-->

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

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

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

</bean>

<!-- (2) -->

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

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

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

</bean>

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

<bean id="userService" class="com.siwuxie095.service.UserService">

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

</bean>

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

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

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

</bean>

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

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

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

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

</bean>

<!-- (3) -->

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

<bean id="transactionManager"

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

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

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

</bean>

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

<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

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

struts.xml:

<?xml version="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>

<package name="demo" extends="struts-default" namespace="/">

<!--

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

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

-->

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

</package>

</struts>

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

web.xml:

<?xml version="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>

<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操作的更多相关文章

  1. JdbcTemplate实现CRUD操作

    ------------------siwuxie095                                     JdbcTemplate 实现 CRUD 操作         1.J ...

  2. 【翻译】MongoDB指南/CRUD操作(四)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...

  3. 【翻译】MongoDB指南/CRUD操作(三)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...

  4. 【翻译】MongoDB指南/CRUD操作(二)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...

  5. 【翻译】MongoDB指南/CRUD操作(一)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...

  6. ASP.NET Core Web API Cassandra CRUD 操作

    在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...

  7. MongoDB的CRUD操作

    1. 前言 在上一篇文章中,我们介绍了MongoDB.现在,我们来看下如何在MongoDB中进行常规的CRUD操作.毕竟,作为一个存储系统,它的基本功能就是对数据进行增删改查操作. MongoDB中的 ...

  8. 【Java EE 学习 44】【Hibernate学习第一天】【Hibernate对单表的CRUD操作】

    一.Hibernate简介 1.hibernate是对jdbc的二次开发 2.jdbc没有缓存机制,但是hibernate有. 3.hibernate的有点和缺点 (1)优点:有缓存,而且是二级缓存: ...

  9. 使用MyBatis对表执行CRUD操作

    一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: <?xml version="1.0&quo ...

随机推荐

  1. 1110 Complete Binary Tree (25 分)

    1110 Complete Binary Tree (25 分) Given a tree, you are supposed to tell if it is a complete binary t ...

  2. 使用oracle导出的dmp文件(包含表结构还是表数据?)

    我们都知道oracle提供了一个exp程序,可以导出dmp文件,那么dmp文件中到底包含哪些东西呢? 1:有对象的信息吗?比如对象的权限? 2:有表空间信息吗? 3:有表结构吗? 4:有表的索引和触发 ...

  3. mysql主从复制——双机互为主从

    第一.mysql主从复制(一主一从)怎么安装mysql数据库,这里不说了,只说它的主从复制,步骤如下:首先需要做一些清理工作,如果之前配置了主从,但是配置失败了.结果会在/var/lib/mysql/ ...

  4. JedisCluster模式尝试进行批量操作

    搭建完redis集群后,可以通过jedis的JedisCluster来访问Redis集群,这里列出使用jedisCluster的spring bean配置方式:   <bean id=" ...

  5. sorted()&enumerate()

    d = {1:2,3:1,44:5,4:5,7:8}l = d.items() #转换为列表print(l)  # dict_items([(1, 2), (3, 1), (44, 5), (4, 5 ...

  6. flask中的蓝图与红图

    内容: 1.flask中的蓝图 2.flask子域名实现 3.flask中的红图 1.flask中的蓝图 一个大型项目中视图比较多,如果仅仅是写在app.py中不方便管理,蓝图就可以做到分功能分目录结 ...

  7. 基于Redis位图实现用户签到功能

    场景需求 适用场景如签到送积分.签到领取奖励等,大致需求如下: 签到1天送1积分,连续签到2天送2积分,3天送3积分,3天以上均送3积分等. 如果连续签到中断,则重置计数,每月初重置计数. 当月签到满 ...

  8. 31. Next Permutation + 46. Permutations + 47. Permutations II + 60. Permutation Sequence

    ▶ 问题:字典序生成有关的问题. ▶ 31. 由当前序列生成字典序里的下一个序列. ● 初版代码,19 ms class Solution { public: void nextPermutation ...

  9. Linux开机挂载windows共享文件夹

    https://blog.csdn.net/zhaogang1993/article/details/79573271  (可行) 命令: mount -t cifs -o username=&quo ...

  10. hive 锁

    HiveQL是一种SQL语言,但缺少udpate和insert类型操作时的行,列或者查询级别的锁支持,hadoop文件通常是一次写入(支持有限的文件追加功能),hadoop和hive都是多用户系统,锁 ...