数据库操作之Spring JDBCTemplate(postgresql)

本文总结了两种使用JDBCTemplate进行数据库CRUD操作的例子,我用的是pg,废话不说,直接开始吧。

先贴一张目录结果图吧:

上图中最主要的是配置文件和所需的各种jar包。

一、通过属性文件的.properties的方式

这种方法很简单,也是最基本的,主要是从配置文件读取数据库连接信息,然后设置到数据源中,再将数据源设置到JdbcTemplate中,通过这个对象进行数据库的CRUD操作。

1、配置文件config.properties

用来配置数据库连接信息,我配置的都是一下基本信息

#数据库地址
db.driverClassName = org.postgresql.Driver
db.url = jdbc:postgresql://127.0.0.1:5432/hcs
db.username = postgres
db.password =postgres
db.initialSize=5
db.maxActive=1000
db.maxIdle=200
db.minIdle=100
db.maxWait=100
db.validationQuery = select version()

2、获取属性文件config.properties

/**
     * 获取属性配置文件
     * @return
     */
    public Properties getProp(){
        InputStream is =  this.getClass().getClassLoader().getResourceAsStream("config.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }

3、创建数据源并获取JdbcTemplate对象

/**
     * 创建数据源并获取JdbcTemplate
     * @return
     */
    BasicDataSource basicDataSource = null;
    public JdbcTemplate getTemplate(){
        basicDataSource = new BasicDataSource();
        Properties pro = getProp();
        basicDataSource.setDriverClassName(pro.getProperty("db.driverClassName"));
        basicDataSource.setUrl(pro.getProperty("db.url"));
        basicDataSource.setUsername(pro.getProperty("db.username"));
        basicDataSource.setPassword(pro.getProperty("db.password"));
        basicDataSource.setValidationQuery(pro.getProperty("db.validationQuery"));
        basicDataSource.setInitialSize(50);
        basicDataSource.setMaxActive(100);
        basicDataSource.setMaxIdle(50);
        basicDataSource.setMinIdle(40);
        basicDataSource.setMaxWait(100);
        basicDataSource.setRemoveAbandoned(true);
        basicDataSource.setRemoveAbandonedTimeout(280);
        basicDataSource.setLogAbandoned(true);
        basicDataSource.setTestOnBorrow(true);
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(basicDataSource);
        return jdbcTemplate;
    }

4、增删改查

增加

/**
     * 保存数据
     * @throws Exception 
     */
    public int saveData(){
        String id = UUID.randomUUID().toString();
        String sql = "INSERT INTO sys_user VALUES('"+id+"','111','111','111','111','111','111','111')";
        int save = 0;
        try {
            save = getTemplate().update(sql);
            close();
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return save;
    }

修改

/**
     * 更新数据
     * @return
     */
    public int updateData(){
        String sql = "UPDATE sys_user SET user_name='hyc',user_login_name = 'hyc' WHERE user_id = ?";
        int update = getTemplate().update(sql,"222");
        close();
        return update;
    }

删除

/**
     * 删除数据
     * @return
     */
    public int deleteData(){
        String sql = "DELETE FROM sys_user WHERE user_id = ?";
        int delete = getTemplate().update(sql,"111");
        close();
        return delete;
    }

查询

    /**
     * 查询数据
     * @return
     */
    public long getData(){
        String sql = "SELECT COUNT(*) FROM sys_user";
        long result = getTemplate().queryForObject(sql, Long.class);
        close();
        return result;
    }

关闭连接方法close()

/**
     * 关闭连接
     */
    public void close(){
        if(null!=basicDataSource){
            try {
                basicDataSource.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

 二、使用xml配置文件

这种方式就是纯Spring方式,需要用到Spring的配置文件,通过IOC和AOP来new对象。

1、Spring配置文件bean.xml(名称自定义,但必须是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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- IOC和DI的注解扫描 -->
    <context:component-scan base-package="com.hyc" ></context:component-scan>

    <!-- 打开AOP的注解 -->
    <!-- 这里用的是中间的横线而不是下划线 -->
    <!-- <aop:aspectj-autoproxy></aop:aspectj-autoproxy> -->

    <!--第一步:配置数据源  -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
        <property name="jdbcUrl" value="jdbc:postgresql://127.0.0.1:5432/hcs"></property>
        <property name="driverClass" value="org.postgresql.Driver"></property>
        <property name="user" value="postgres"></property>
        <property name="password" value="hyc123"></property>
    </bean>

    <!-- 第二步:将数据源设置JdbcTemplate模板中 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 第三步:在dao中注入JdbcTemplate模板 -->
    <bean id="sysUserDao" class="com.hyc.dao.SysUserDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!-- 第四步:在service中注入dao -->
    <bean id="sysUserService" class="com.hyc.service.SysUserService">
        <property name="sysUserDao" ref="sysUserDao"></property>
    </bean>

</beans>

2、创建dao层,将JdbcTemplate作为其属性,并添加get和set方法,这样就可以在dao层调用模板对象

/**
 * DAO层
 * 
 * @createtime 2017年10月31日 下午4:39:44
 * @description
 */
public class SysUserDao {

    private JdbcTemplate jdbcTemplate;

    
    /**
     * @return the jdbcTemplate
     */
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    /**
     * @param jdbcTemplate
     *            the jdbcTemplate to set
     */
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

3、创建service层,并将dao层作为其属性,提供get和set方法,这样就可以在service中调用dao对象及其中的方法了

/***
 * service层
 * @createtime 2017年10月31日 下午4:39:31
 * @description
 */
public class SysUserService {
     
    private SysUserDao sysUserDao;

    
    /**
     * @return the sysUserDao
     */
    public SysUserDao getSysUserDao() {
        return sysUserDao;
    }


    /**
     * @param sysUserDao the sysUserDao to set
     */
    public void setSysUserDao(SysUserDao sysUserDao) {
        this.sysUserDao = sysUserDao;
    }
    
}

4、在DAO中调用JdbcTemplate对象进行数据库的CRUD操作
增加

/**
     * 新增用户
     * @param sysUser
     * @return
     */
    public int addUser(SysUser sysUser) {
        String sql = "INSERT INTO sys_user VALUES('" + sysUser.getUserId()
                + "','" + sysUser.getUserName() + "','"
                + sysUser.getUserRealName() + "','" + sysUser.getUserCode()
                + "','" + sysUser.getUserLoginName() + "','"
                + sysUser.getUserDeptId() + "','" + sysUser.getIsdepadmin()
                + "','" + sysUser.getFreecapacity() + "')";
        int save = 0;
        try {
            save = jdbcTemplate.update(sql);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return save;
    }

删除

/**
     * 删除用户
     * @param userId
     * @return
     */
    public int delUser(String userId){
        String sql = "DELETE FROM sys_user WHERE user_id = ?";
        return jdbcTemplate.update(sql, "d83ea6cf-4f78-4fd4-ac4f-bb32ec706af5");
    }

修改

/**
     * 修改用户信息
     * @param sysUser
     * @return
     */
    public int updateUser(SysUser sysUser){
        String sql = "UPDATE sys_user SET user_name=?,user_login_name = ? WHERE user_id = ?";
        return jdbcTemplate.update(sql, sysUser.getUserName(),sysUser.getUserLoginName(),sysUser.getUserId());
        
    }

查看

/**
     * 查看用户
     * @param userId
     * @return
     */
    public Map<String, Object> viewUser(String userId){
        String sql = "SELECT * FROM sys_user WHERE user_id=?";
        return jdbcTemplate.queryForMap(sql,userId);
    }

5、在service层(业务逻辑层)通过dao对象进行调用数据库操作相关的方法

    //
    public int saveUser(SysUser sysUser){
        return sysUserDao.addUser(sysUser);
    }
    
    //
    public int delUser(String userId){
        return sysUserDao.delUser(userId);
    }
    
    //
    public int updateUser(SysUser sysUser){
        return sysUserDao.updateUser(sysUser);
    }
    
    //
    public Map<String, Object> viewUser(String userId){
        return sysUserDao.viewUser(userId);
    }

6、创建pojo对象,即service中的SysUser,也是数据库表所映射的对象(ORM)
要提供所有属性的get和set方法

  1 package com.hyc.dao;
  2 
  3 public class SysUser {
  4     private String userId;
  5     private String userName;
  6     private String userRealName;
  7     private String userCode;
  8     private String userLoginName;
  9     private String userDeptId;
 10     private String isdepadmin;
 11     private String freecapacity;
 12 
 13     /**
 14      * @return the userId
 15      */
 16     public String getUserId() {
 17         return userId;
 18     }
 19 
 20     /**
 21      * @param userId
 22      *            the userId to set
 23      */
 24     public void setUserId(String userId) {
 25         this.userId = userId;
 26     }
 27 
 28     /**
 29      * @return the userName
 30      */
 31     public String getUserName() {
 32         return userName;
 33     }
 34 
 35     /**
 36      * @param userName
 37      *            the userName to set
 38      */
 39     public void setUserName(String userName) {
 40         this.userName = userName;
 41     }
 42 
 43     /**
 44      * @return the userRealName
 45      */
 46     public String getUserRealName() {
 47         return userRealName;
 48     }
 49 
 50     /**
 51      * @param userRealName
 52      *            the userRealName to set
 53      */
 54     public void setUserRealName(String userRealName) {
 55         this.userRealName = userRealName;
 56     }
 57 
 58     /**
 59      * @return the userCode
 60      */
 61     public String getUserCode() {
 62         return userCode;
 63     }
 64 
 65     /**
 66      * @param userCode
 67      *            the userCode to set
 68      */
 69     public void setUserCode(String userCode) {
 70         this.userCode = userCode;
 71     }
 72 
 73     /**
 74      * @return the userLoginName
 75      */
 76     public String getUserLoginName() {
 77         return userLoginName;
 78     }
 79 
 80     /**
 81      * @param userLoginName
 82      *            the userLoginName to set
 83      */
 84     public void setUserLoginName(String userLoginName) {
 85         this.userLoginName = userLoginName;
 86     }
 87 
 88     /**
 89      * @return the userDeptId
 90      */
 91     public String getUserDeptId() {
 92         return userDeptId;
 93     }
 94 
 95     /**
 96      * @param userDeptId
 97      *            the userDeptId to set
 98      */
 99     public void setUserDeptId(String userDeptId) {
100         this.userDeptId = userDeptId;
101     }
102 
103     /**
104      * @return the isdepadmin
105      */
106     public String getIsdepadmin() {
107         return isdepadmin;
108     }
109 
110     /**
111      * @param isdepadmin
112      *            the isdepadmin to set
113      */
114     public void setIsdepadmin(String isdepadmin) {
115         this.isdepadmin = isdepadmin;
116     }
117 
118     /**
119      * @return the freecapacity
120      */
121     public String getFreecapacity() {
122         return freecapacity;
123     }
124 
125     /**
126      * @param freecapacity
127      *            the freecapacity to set
128      */
129     public void setFreecapacity(String freecapacity) {
130         this.freecapacity = freecapacity;
131     }
132 
133 }
View Code

7、编写单元测试用例,测试增删改查
在增删改查之前需要获取service对象,而service对象是通过配置文件注入的,所以要通过配置文件的getBean方法获取,这部分代码数据全局变量,所以可以写在junit的before方法中

获取service对象

 

    ApplicationContext context = null;
    SysUserService sysUserService = null;
    @Before
    public void before(){
        context = new ClassPathXmlApplicationContext("bean.xml");
        sysUserService = context.getBean("sysUserService",SysUserService.class);
    }

 

测试增删改查

//测试增加操作
    @Test
    public void testSaveUser(){
        SysUser sysUser= new SysUser();
        sysUser.setUserId(UUID.randomUUID().toString());
        sysUser.setUserName("hyc2");
        sysUser.setUserRealName("hyc2");
        sysUser.setUserCode("sss");
        sysUser.setUserLoginName("hyc2");
        sysUser.setUserDeptId("ddd");
        sysUser.setIsdepadmin("1");
        sysUser.setFreecapacity("20");
        int save = sysUserService.saveUser(sysUser);
        System.out.println(save==1?"保存成功":"保存失败");
    }
    
    //测试删除操作
    @Test
    public void testDelUser(){
        int del = sysUserService.delUser("4436b3c2-381f-4bc3-8a4c-0a935b30af68");
        System.out.println(del==1?"删除成功":"删除失败");
    }
    
    //测试修改操作
    @Test
    public void testUpdateUser(){
        SysUser sysUser= new SysUser();
        sysUser.setUserId("441c0c98-f150-45f2-84ca-c0be1b944275");
        sysUser.setUserName("hyc222");
        sysUser.setUserRealName("hyc222");
        sysUser.setUserCode("sss22");
        sysUser.setUserLoginName("hyc222");
        sysUser.setUserDeptId("ddd");
        sysUser.setIsdepadmin("1");
        sysUser.setFreecapacity("20");
        int update = sysUserService.updateUser(sysUser);
        System.out.println(update==1?"修改成功":"修改失败");
    }
    
    //测试查询操作
    @Test
    public void testViewUser(){
        Map<String, Object> sysUser = sysUserService.viewUser("222");
        System.out.println("用户名是:"+sysUser.get("user_name"));
    }

以上就是所有内容,已经测试,如果按照步骤即可跑起来,但是我的CRUD都是最简单的,主要是介绍这两种方法的框架搭建。

推荐一篇比较好的博客:----->http://www.cnblogs.com/tuhooo/p/6491913.html,作者在对xml配置文件中配置原理部分的描述比较通俗易懂,可借鉴。

 

posted @ 2017-11-01 19:32  bug改了我  阅读(7901)  评论(0编辑  收藏  举报