码迷,mamicode.com
首页 > 编程语言 > 详细

【Spring】对持久层技术的整合

时间:2019-08-15 05:59:06      阅读:19      评论:0      收藏:0      [点我收藏+]

标签:out   artifact   number   iba   user   rownum   figure   http   返回   

一、持久层技术

  1. Spring 中自带的 JdbcTemplate
  2. Hibernate
  3. Mybatis

二、JdbcTemplate

开发步骤:

1. 导入相关的jar包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
    
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>

2. 配置连接池(数据源)

  创建一个数据库test

  • Spring默认的连接池:
<!-- 配置Spring默认的连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="root"/>
    <property name="password" value="123"/>
</bean>
  • DBCP连接池:

  引入Maven 坐标:

<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>

  配置信息:

<!-- 配置DBCP连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql:///test"/>
    <property name="username" value="root"/>
    <property name="password" value="123"/>
</bean>
  • C3P0连接池:

  引入Maven 坐标:

<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>

  配置信息:

<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///test"/>
    <property name="user" value="root"/>
    <property name="password" value="123"/>
</bean>
将参数设置到属性文件中:

属性文件jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///test
jdbc.user = root
jdbc.password = 123

需要在applicationContext.xml 中使用属性文件配置的内容.

  • 第一种写法:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:jdbc.properties"></property>
</bean>
  • 第二种写法:

  需要引入context的命名空间:

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    

  配置如下:

<context:property-placeholder location="classpath:jdbc.properties"/>

  上面数据源的配置,属性的值就可以用${}来取出properties配置文件中的值

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.user}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

3. 创建表

这里要注意的是创建的表名不能用users,

CREATE TABLE `member` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

4. 编写实体类

public class Member {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Member [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

5. Dao层实现

5.1 继承JdbcDaoSupport

Spring框架中提供了对持久层技术支持的类: JdbcDaoSupport,这个类中依赖了JdbcTemplte模版而且自己实现了setter方法

  编写DAO的时候要继承该类,如下:

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.hao.entity.Member;

public class MemberDao extends JdbcDaoSupport {

    /**
     * 添加用户
     * 
     * @param member
     */
    public void add(Member member) {
        String sql = "insert into member values(null,?,?)";
        this.getJdbcTemplate().update(sql, member.getName(), member.getAge());
    }

    /**
     * 根据id更新用户名
     * 
     * @param member
     */
    public void updateById(Member member) {
        String sql = "update member  set name = ? where id =?";
        this.getJdbcTemplate().update(sql, member.getName(), member.getId());
    }

    /**
     * 根据id删除用户
     * 
     * @param member
     */
    public void deleteById(Member member) {
        String sql = "delete from member where id = ? ";
        this.getJdbcTemplate().update(sql, member.getId());
    }

    /**
     * 查询用户总数
     * 
     * @return
     */
    public int findCount() {
        String sql = "select count(*) from member";
        // spring 3.2之后的版本不在支持queryInt(sql);
        return this.getJdbcTemplate().queryForObject(sql, int.class);
    }

    /**
     * 通过id查询用户名
     * 
     * @param id
     * @return
     */
    public String findNameById(int id) {
        String sql = "select name from member where id = ?";
        return this.getJdbcTemplate().queryForObject(sql, String.class, id);
    }

    /**
     * 根据id查询用户
     * 
     * @param id
     * @return
     */
    public Member findById(int id) {
        String sql = "select * from member where id = ?";
        Member member = this.getJdbcTemplate().queryForObject(sql, new UserRowMapper(), id);
        return member;
    }

    /**
     * 查询所有用户
     * 
     * @return
     */
    public List<Member> findAll() {
        String sql = "select * from member";
        return this.getJdbcTemplate().query(sql, new UserRowMapper());

    }

    class UserRowMapper implements RowMapper<Member> {
        /**
         * rs:结果集. rowNum:行号
         */
        public Member mapRow(ResultSet rs, int rowNum) throws SQLException {
            Member member = new Member();
            member.setId(rs.getInt("id"));
            member.setName(rs.getString("name"));
            return member;
        }

    }
}

  在XML中的配置,此种方式不需要再XML中声明jdbcTemplate ,只需要在Dao层注入数据源即可如下:

<context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean> 

    <!-- 此处直接注入数据源,因为Dao层中继承了JdbcDaoSupport这个类 -->
    <bean id="memberDao" class="com.hao.dao.MemberDao">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
5.2 直接注入JdbcTmplate

public class MemberDaoForNoExtend {
  
    //利用setter的方法注入jdbcTmplate
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    /**
     * 添加用户
     * 
     * @param member
     */
    public void add(Member member) {
        String sql = "insert into member values(null,?,?)";
        jdbcTemplate.update(sql, member.getName(), member.getAge());
    }
    
   // 后面的代码省略...
    
}

  在XML中的配置,此种方式要在Dao层注入jdbcTemplate

<!-- 定义jdbctemplate 需要注入数据源 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
</bean>
<!-- 定义Dao层类 需要注入jdbcTemplate-->
<bean id="memberDao" class="com.hao.dao.MemberDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

6. 测试

  测试1 --> 5.1中的方式测试

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.hao.dao.MemberDao;
import com.hao.entity.Member;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext1.xml")
public class JDBCTest1 {

    @Autowired
    @Qualifier("memberDao")
    private MemberDao memberDao;

    @Test
    public void test1() {
        Member member = new Member();
        member.setName("小涛");
        member.setAge(23);
        memberDao.add(member);
    }
    
    @Test
    public void test2() {
        int findCount = memberDao.findCount();
        System.out.println(findCount);
    }
    
    @Test
    public void test3() {
        Member member  = new Member();
        member.setId(12);
        memberDao.deleteById(member);
    }

}

  测试2 --> 5.2中的方式测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class JDBCTest2 {
    
    @Autowired
    @Qualifier("memberDaoForNoExtend")
    private MemberDaoForNoExtend memberDaoForNoExtend;
    
    @Test
    public void test1() {
        Member member = new Member();
        member.setName("小明");
        member.setAge(23);
        memberDaoForNoExtend.add(member);
    }
}

JdbcTemplate 的CRUD(待整理)

  • 保存:update(String sql,Object... args)
  • 修改:update(String sql,Object... args)
  • 删除:update(String sql,Object... args)
  • 查询:
    • 简单查询:
      • queryForObject(String sql,Class clazz,Object... args);
    • 复杂查询:(返回对象,和对象集合)
      • queryForObjectString sql,RowMapper<T> rowMapper,Object... args);
      • query(String sql,RowMapper<T> rowMapper,Object... args);

三、Hibernate

org.springframework.orm.hibernate3.support.HibernateDaoSupport

四、MyBatis

org.springframework.orm.ibatis.support.SqlMapClientDaoSupport

【Spring】对持久层技术的整合

标签:out   artifact   number   iba   user   rownum   figure   http   返回   

原文地址:https://www.cnblogs.com/haoworld/p/spring-dui-chi-jiu-ceng-ji-shu-de-zheng-he.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!