Spring系列之訪問數據庫


一、概述

  Spring的數據訪問層是以統一的數據訪問異常層體系為核心,結合JDBC API的最佳實踐和統一集成各種ORM方案,完成Java平台的數據訪問。

二、JDBC API的最佳實踐

  Spring提供兩種JDBC API的最佳實踐,一種是以JDBCTemplate為核心的基於Template的JDBC使用方式,另一種則是在JdbcTemplate基礎之上構建的基於操作對象的JDBC使用方式。

  1、基於Template的JDBC使用方式

  Spring框架提出了org.springframework.jdbc.core.JdbcTemplate作為數據訪問的Helper類,JDBCTemplate是整個Spring數據抽象層提供的所有JDBC API最佳實踐的基礎。

  jdbcTemplate主要關注以下事情:

  • 封裝所有基於JDBC的數據訪問代碼,以統一格式和規范來使用JDBC API。
  • 對SQLException所提供的異常信息在框架內進行統一轉譯,統一了數據接口的定義,簡化了客戶端代碼對數據訪問異常的處理。

  下面簡單介紹JdbcTemplate的使用示例。

  首先是在Spring的IoC容器中配置數據源和JdbcTemplate。

<?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-4.1.xsd">
    
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
       <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 配置Spring的JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>    
</beans>

  其中,db.properties內容為:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?characterEncoding=utf-8
jdbc.username=root
jdbc.password=281889

  接下來就可以編寫測試類:

public class JDBCTest
{
    private ApplicationContext applicationContext=null;
    private JdbcTemplate jdbcTemplate;
    {
        applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
    }    
    @Test
    public void test()
    {
        DataSource dataSources=applicationContext.getBean(DataSource.class);
        System.out.println(dataSources.toString());
    }
    /**
     * 根據id查詢用戶信息
     */
    @Test
    public void testFindUserById()
    {
        String sql="select * from User where id=2";
        
        Map<String, Object> map=jdbcTemplate.queryForMap(sql);
        for(String s:map.keySet())
        {
            System.out.println(s+":"+map.get(s));
        }
    }
    /**
     * 查到實體類集合
     */
    @Test
    public void testQueryForList()
    {
        String sql="select * from User where id>?";
        RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
        List<User> list=jdbcTemplate.query(sql, rowMapper,2);
        for (User user : list)
        {
            System.out.println(user.getUsername());
        }
    }
    /**
     * 從數據庫中獲取一條記錄,實際得到對應的一個對象
     */
    @Test
    public void getUserById()
    {
        String sql="select * from User where id=?";
        RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
        User user=jdbcTemplate.queryForObject(sql, rowMapper,1);
        System.out.println(user.getUsername());
    }
    /**
     * 統計查詢
     */
    @Test
    public void testQueryForCount()
    {
        String sql="select count(id) from user";
        long count=jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(count);
    }
}

  2、基於操作對象的JDBC使用方式

  Spring除了提供基於Template形式的JDBC形式,還對各種數據庫操作以面向對象的形式進行建模。在這種基於操作對象的JDBC使用方式中,查詢、更新、調用存儲過程等數據訪問操作,被抽象為操作對象,這些操作對象統一定義在org.springframework.jdbc.object包下。

三、Spring對ORM的集成

  Spring對當前各種流行的ORM解決方案的集成主要體現在以下幾個方面:

  • 統一的資源管理方式
  • 特定於ORM的數據訪問異常到Spring統一異常體系的轉譯
  • 統一的數據訪問事務管理及控制方式

  1、Spring對Mybatis的集成

  實現mybatis和Spring進行整合,通過Spring管理SqlSessionFactory、mapper接口。

  整個需要的jar包:

  

  構建Myba配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--加載映射文件 
        使用自動掃描器時,mapper.xml文件如果和mapper.java接口在一個目錄則此處不用定義mappers 
    -->
    <mappers>
         <package name="com.demo.ssm.mapper"/>
    </mappers>

  構建Spring配置文件:

  在classpath下創建applicationContext.xml,定義數據庫鏈接池、SqlSessionFactory。

<?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-4.1.xsd">

    <context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="10"/> <property name="maxIdle" value="5"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--加載mybatis的配置文件 --> <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property> <!-- 數據源 --> <property name="dataSource" ref="dataSource"></property> </bean> </beans>

  編寫Mapper,這里有三種方法

  • 第一種方法:Dao接口實現類繼承SqlSessionDaoSupport

  使用此種方法即原始dao開發方法,需要編寫dao接口,dao接口實現類、映射文件。

  1、sqlMapConfig.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--加載映射文件 
        使用自動掃描器時,mapper.xml文件如果和mapper.java接口在一個目錄則此處不用定義mappers 
    -->
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
    </mappers>
</configuration>

  2、定義dao接口

public interface UserDao
{
    public User getUserById(int id) throws Exception;

}

  3、dao接口實現類繼承SqlSessionDaoSupport

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao
{
    public User getUserById(int id) throws Exception
    {
        // 繼承SqlSessionDaoSupport
        SqlSession session = this.getSqlSession();
        User user = null;
        // 通過sqlsession調用selectOne方法獲取一條結果集
        // 參數1:指定定義的statement的id,參數2:指定向statement中傳遞的參數
        user = session.selectOne("test.findUserById", id);
        return user;
    }
}

  4、Spring配置文件

  <!-- 原始dao接口 -->
    <bean id="userDao" class="com.demo.ssm.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

  5、編寫測試類測試運行

public class UserDaoImplTest
{
    private ApplicationContext applicationContext;
    @Before
    public void setup()
    {
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    @Test
    public void testGetUserById() throws Exception
    {
        UserDao userDao=(UserDao) applicationContext.getBean("userDao");
        User user=userDao.getUserById(1);
        System.out.println(user);
    }
}
  • 第二種方法:使用org.mybatis.spring.mapper.MapperFactoryBean

  此方法即mapper接口開發方法,只需定義mapper接口,不用編寫mapper接口實現類。每個mapper接口都需要在spring配置文件中定義

  1、在sqlMapConfig.xml中配置mapper.xml的位置

  如果mapper.xml和mappre接口的名稱相同且在同一個目錄,這里可以不用配置

  2、定義mapper接口

public interface UserMapper
{
    //根據用戶id查詢用戶信息
    public User findUserById(int id) throws Exception;
}

  3、Spring中定義

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.demo.ssm.mapper.UserMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean> 

  4、編寫測試類測試運行

public class UserMapperTest
{
    private ApplicationContext applicationContext;
    @Before
    public void setup()
    {
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    @Test
    public void testGetUserById() throws Exception
    {
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        User user=userMapper.findUserById(1);
        System.out.println(user);
    }
}
  • 第三種方法:使用mapper掃描器

  此方法即mapper接口開發方法,只需定義mapper接口,不用編寫mapper接口實現類。只需要在spring配置文件中定義一個mapper掃描器,自動掃描包中的mapper接口生成代代理對象。

  1、mapper.xml文件編寫

  2、定義mapper接口

  注意:mapper.xml的文件名和mapper的接口名稱保持一致,且放在同一個目錄

  3、配置mapper掃描器

<!-- mapper批量掃描,從mapper包中掃描成mapper接口,自動創建 代理對象並在Spring容器中注冊
        自動掃描出來的mapper的bean的id為mapper類型(首字母小寫)
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定掃描的包名 -->
        <property name="basePackage" value="com.demo.ssm.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM