05_ssm基础(四)之Spring与持久层的整合

30.31.spring对jdbc的支持jdbcTemplate

  

  使用Spring的JDBC准备:
  1):拷贝jar:
       mysql-connector-java-5.1.11.jar:MySQL驱动包
       spring-jdbc-4.1.2.RELEASE.jar:支持JDBC
       spring-tx-4.1.2.RELEASE.jar: 支持事务
  2): 操作Product对象的DAO实现:
  3):参考文档:参考Spring4.x文档的362页.

代码:如下

   spring配置文件代码

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7          http://www.springframework.org/schema/context
 8           http://www.springframework.org/schema/context/spring-context.xsd">
 9     <!--  读取配置文件-->
10     <context:property-placeholder location="classpath:db.properties"/>
11     <!--配置dataSources-->
12     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
13         <property name="driverClassName" value="${mysql.driverClass}"/>
14         <property name="url" value="${mysql.JdbcUrl}"/>
15         <property name="username" value="${mysql.User}"/>
16         <property name="password" value="${mysql.Password}"/>
17     </bean>
18
19     <bean id="product2Dao" class="com.day02.ssm.spring.dao.impl.Product2Dao">
20         <property name="dataSource" ref="dataSource"/>
21     </bean>
22 </beans>

   dao是实现代码:

 1 package com.day02.ssm.spring.dao.impl;
 2
 3 import com.day02.ssm.spring.dao.IProductDao;
 4 import com.day02.ssm.spring.model.Product;
 5 import org.apache.commons.dbcp.BasicDataSource;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.jdbc.core.RowMapper;
 9
10 import javax.sql.DataSource;
11 import java.sql.Connection;
12 import java.sql.PreparedStatement;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15
16 /**
17  * 课程笔记:http://www.cnblogs.com/newAndHui/category/1153640.html
18  * 疑问咨询wx:851298348
19  */
20 public class Product2Dao implements IProductDao {
21     private JdbcTemplate jdbcTemplate;
22
23
24     public void setDataSource(DataSource dataSource) {
25         this.jdbcTemplate = new JdbcTemplate(dataSource);
26     }
27
28     @Override
29     public void save(Product product)  {
30         String sql = "INSERT INTO product (product_name,sale_price) VALUES (?,?)";
31         this.jdbcTemplate.update(sql,product.getProductName(),product.getSalePrice());
32     }
33
34     @Override
35     public void delete(int id) {
36         String sql="DELETE FROM product WHERE id=?";
37         this.jdbcTemplate.update(sql,id);
38
39     }
40
41     @Override
42     public void update(Product product) {
43        String sql="UPDATE product SET sale_price=? WHERE id=?";
44         this.jdbcTemplate.update(sql,product.getSalePrice(),product.getId());
45     }
46
47     @Override
48     public Product query(int id) {
49         String sql="SELECT id,product_name,sale_price FROM product WHERE id=?";
50         Product product = this.jdbcTemplate.queryForObject(sql, new Object[]{id}, new RowMapper<Product>() {
51                                     public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
52                                         Product product = new Product();
53                                         product.setId(rs.getInt("id"));
54                                         product.setProductName(rs.getString("product_name"));
55                                         product.setSalePrice(rs.getInt("sale_price"));
56                                         return product;
57                                     }
58                                 });
59         return product;
60     }
61 }

Product2Dao

  dao测试代码

 1 package com.day02.ssm.spring.test;
 2
 3 import com.day02.ssm.spring.dao.impl.Product2Dao;
 4 import com.day02.ssm.spring.model.Product;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10
11 /**
12  * 课程笔记:http://www.cnblogs.com/newAndHui/category/1153640.html
13  * 疑问咨询wx:851298348
14  */
15 @RunWith(SpringJUnit4ClassRunner.class)//把junit加载到spring容器中去
16 @ContextConfiguration("classpath:spring-config_jdbcTemplat.xml")
17 public class TestProduct2Dao {
18
19     // private ProductDao productDao=new ProductDao();
20     @Autowired
21     private Product2Dao productDao;//从spring中获取dao对象
22
23     @Test
24     public void test() {
25         Product product = new Product();
26         product.setProductName("苹果22");
27         product.setSalePrice(892);
28         productDao.save(product);
29     }
30     @Test
31     public void testDelete() {
32        productDao.delete(24);
33     }
34
35     @Test
36     public void testUpdate() {
37         Product product = new Product();
38         product.setId(23);
39         product.setSalePrice(1000);
40         productDao.update(product);
41     }
42     @Test
43     public void testQuery() {
44         Product query = productDao.query(23);
45         System.out.println("query="+query);
46     }
47
48 }

TestProduct2Dao

32.spring对jdbc的支持jdbcTemplate之继承方式

  注意:和上面原理一样,只是写法不一样

  

33.spring与mybatis集成方案1

  依赖包:

  

  xml文件配置:

  

  映射文件:

  

  dao实现:

  

34.spring与mybatis整合方案2(不写实现类)

  

34.spring与mybatis整合方案3(终极生产版本)

  

   spring与mybatis整合终极版本代码:

    整合的xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7          http://www.springframework.org/schema/context
 8           http://www.springframework.org/schema/context/spring-context.xsd">
 9     <!--  读取配置文件-->
10     <context:property-placeholder location="classpath:db.properties"/>
11     <!--配置dataSources-->
12     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
13         <property name="driverClassName" value="${mysql.driverClass}"/>
14         <property name="url" value="${mysql.JdbcUrl}"/>
15         <property name="username" value="${mysql.User}"/>
16         <property name="password" value="${mysql.Password}"/>
17     </bean>
18 <!--整合mybatis-->
19     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
20        <!--数据源-->
21         <property name="dataSource" ref="dataSource"/>
22         <!--属性文件-->
23         <!--映射文件地址-->
24         <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
25     </bean>
26
27     <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
28         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
29         <property name="basePackage" value="com.day03.ssm.spring.mybatis.dao"/>
30     </bean>
31
32    <!-- <bean id="mapperFactoryBean" class="org.mybatis.spring.mapper.MapperFactoryBean">
33         <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
34         <property name="mapperInterface" value="com.day03.ssm.spring.mybatis.dao.IProduct2Dao"/>
35     </bean>-->
36
37    <!-- <bean id="productDao" class="com.day03.ssm.spring.mybatis.dao.impl.ProductDao">
38         <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
39     </bean>-->
40
41
42
43
44 </beans>

  mybatis映射文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4       <!--
 5       namespace:该映射文件的名字,理论上可以任意取
 6                  没有实现类时 命名空间必须为dao接口的权限命名地址
 7       -->
 8 <mapper namespace="com.day03.ssm.spring.mybatis.dao.IProduct2Dao">
 9    <insert id="save" parameterType="com.day03.ssm.spring.mybatis.model.Product">
10       INSERT INTO product (product_name,sale_price) VALUES (#{productName},#{salePrice})
11    </insert>
12 </mapper>

  测试代码:

 1 package com.day03.ssm.spring.mybatis.testDao;
 2
 3 import com.day03.ssm.spring.mybatis.dao.IProduct2Dao;
 4 import com.day03.ssm.spring.mybatis.model.Product;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10
11 /**
12  * 课程笔记:http://www.cnblogs.com/newAndHui/category/1153640.html
13  * 疑问咨询wx:851298348
14  */
15 @RunWith(SpringJUnit4ClassRunner.class)//把junit加载到spring容器中去
16 @ContextConfiguration("classpath:spring-config3.xml")
17 public class TestProduct3Dao {
18     @Autowired
19     private IProduct2Dao productDao;
20
21     @Test
22     public void testSave() {
23         Product product = new Product();
24         product.setProductName("小米33");
25         product.setSalePrice(789);
26         productDao.save(product);
27     }
28 }

TestProduct3Dao

  

原文地址:https://www.cnblogs.com/newAndHui/p/9068234.html

时间: 2024-08-29 09:31:53

05_ssm基础(四)之Spring与持久层的整合的相关文章

对spring 对持久层的支持和数据库连接池的理解

1.spring对持久层的支持在于,得到数据库连接之后操作上的封装,将操作简化了.也就是说以后操作sql语句就用XXXTemplate对象了. 2.数据库连接池的作用只在于得到数据库的连接,并对数据库的连接做管理,不涉及到得到连接后的操 所以,spring对持久层的支持的XXXTemplate类是属于spring包下的,是spring的支持.但是数据库连接池的获取连接的数据源对象XXXDataSource对象是在第三方包内的,比如c3p0和dbcp包 3.所以不同的XXXTemplate可以和不

Spring 对持久层的支持(DAO)应用

Spring提供了模板类:     使用模板类有两种使用方式:     1.手动在dao层加上一个模板类属性       public class UserDaoImpl implements UserDao{            private  JdbcTemplate tem;//需要在配置文件中去注入该属性       } 2.让dao的实现类继承daoSupport      public class UserDaoImpl extends  JdbcDaoSupport  impl

Spring(七)持久层

一.Spring对DAO的支持 DAO:Data Access Object Spring提供了DAO框架,让开发人员无须耦合特定的数据库技术,就能进行应用程序的开发. Spring封闭了操作Oracle,MySql,DB2,SQL等数据库的用法. 它们都实现同一接口,方法也是一样的. 优势: 由于依赖于接口,可以通过依赖注入随时替换DAO接口的实现类,而应用程序完全不用了解接口与底层数据库操作细节. 应用程序----调用----->DAO接口<---实现--DAO接口实现类----操作---

springMVC系列之(四) spring+springMVC+hibernate 三大框架整合(转)

https://blog.csdn.net/lishehe/article/details/38356261 基于spring+springmvc+hibernate的maven项目搭建 https://blog.csdn.net/fancy_t/article/details/70989754 原文地址:https://www.cnblogs.com/1987721594zy/p/9708567.html

Spring Boot学习记录(三)--整合Mybatis

Spring Boot学习记录(三)–整合Mybatis 标签(空格分隔): spring-boot 控制器,视图解析器前面两篇都已弄好,这一篇学习持久层框架整合. 1.数据源配置 数据源使用druid,maven引入相关依赖,包括spring-jdbc依赖,mysql依赖 1.转换问题 配置的过程要学会为什么这样配置,而不是只学会了配置.这里我们可以和以前的配置方式对比: 以前版本 <!--配置数据库连接池Druid--> <bean id="dataSource"

Spring的四个基本注解annotation(控制层,业务层,持久层) @Component、@

SpringMVC中四个基本注解: @Component.@Repository   @Service.@Controller 看字面含义,很容易却别出其中三个: @Controller    控制层,就是我们的action层 @Service        业务逻辑层,就是我们的service或者manager层 @Repository  持久层,就是我们常说的DAO层 而@Component  (字面意思就是组件),它在你确定不了事哪一个层的时候使用. 其实,这四个注解的效果都是一样的,Sp

第五章 征服数据库(Spring对DB的使用)——开发持久层

本章内容: 定义Spring对数据库访问的支持 配置数据库资源 使用Spring的JDBC模板 在几乎所有的企业级应用中,都需要构建数据持久层.现在意义上的数据持久层是指把对象或者数据保存到数据库中,以及从数据库中取出数据. Spring提供了一组数据访问框架,它集成了多种数据访问技术.不管是JDBC.iBATIS还是Hibernate. ? 一.Spring的数据访问哲学 Spring开发者一直坚持的一个目标之一就是:允许开发人员在开发应用软件时能够遵循面向对象原则的"针对接口编程"

SpringBoot2.0 基础案例(09):集成JPA持久层框架,简化数据库操作

一.JAP框架简介 JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范.主要是为了简化持久层开发以及整合ORM技术,结束Hibernate.TopLink.JDO等ORM框架各自为营的局面.JPA是在吸收现有ORM框架的基础上发展而来,易于使用,伸缩性强. 二.与SpringBoot2.0整合 1.核心依赖 <!-- JPA框架 --> <dependency> <groupId>org.sp

Spring Boot 入门之持久层篇(三)

原文地址:Spring Boot 入门之持久层篇(三) 博客地址:http://www.extlight.com 一.前言 上一篇<Spring Boot 入门之 Web 篇(二)>介绍了 Spring Boot 的 Web 开发相关的内容,项目的开发离不开数据,因此本篇开始介绍持久层相关的知识. 二.整合 JdbcTemplate 2.1 添加依赖 <dependency> <groupId>org.springframework.boot</groupId&g