Spring框架简介⑨

JDBCTemplate框架的简单使用(实际工作中使用较少)

引包

链接:https://pan.baidu.com/s/1lyoSeLmkkFJurBF_4GFH4g 密码:hyz8

先上第一个例子, 建立数据库表我省略了...

配置文件:

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

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_10"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <!-- 初始化连接数 -->
        <property name="initialSize" value="1"></property>
        <!-- 最大连接数 -->
        <property name="maxActive" value="5"></property>
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="2"></property>
        <!-- 最小空闲连接数 -->
        <property name="minIdle" value="1"></property>
    </bean>
    
    <bean id="userDao" class="com.rl.spring.dao.impl.UserDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="userService" class="com.rl.spring.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>

UserDaoImpl类:

package com.rl.spring.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.rl.spring.dao.UserDao;
import com.rl.spring.model.User;

public class UserDaoImpl implements UserDao {
    
    //需要引入数据源
    private DataSource dataSource;
    
    private JdbcTemplate jt;
    
    /**
     * 使用配置文件的方式注入必须提供set方法
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jt = new JdbcTemplate(dataSource);
    }

    /**
     * 对于save跟update的方法 都是采用jt.update()
     * userId自增
     */
    @Override
    public void saveUser(User user) {
        String sql = "insert into t_user values(null, ?, ?)";
        jt.update(sql, new Object[] {user.getUsername(), user.getPassword()});
    }

   
}

UserServiceImpl类:

package com.rl.spring.service.impl;

import java.util.List;

import com.rl.spring.dao.UserDao;
import com.rl.spring.model.User;
import com.rl.spring.service.UserService;
public class UserServiceImpl implements UserService {

    private UserDao userDao;
    
    /**
     * 使用配置文件的方式注入, 必须提供set方法
     * @param userDao
     */
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void saveUser(User user) {
        userDao.saveUser(user);
    }

    
}

测试代码:

package com.rl.spring.test;

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

import com.rl.spring.model.User;
import com.rl.spring.service.UserService;

@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:ApplicationContext.xml"})
public class TestSpring {
	
    @Autowired
    UserService userService;
    
    @Test
    public void test() {
        User user = new User();
        user.setUsername("lijialin");
        user.setPassword("123");
        userService.saveUser(user);
    }
    
}

数据库展示结果:

接下来:

修改:

UserDaoImpl类:

package com.rl.spring.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.rl.spring.dao.UserDao;
import com.rl.spring.model.User;

public class UserDaoImpl implements UserDao {
    
    //需要引入数据源
    private DataSource dataSource;
    
    private JdbcTemplate jt;
    
    /**
     * 使用配置文件的方式注入必须提供set方法
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jt = new JdbcTemplate(dataSource);
    }

    

    @Override
    public void updateUser(User user) {
        String sql = "update t_user t set t.username = ?, t.password=? where t.user_id=?";
        jt.update(sql, new Object[] {user.getUsername(), user.getPassword(), user.getUserId()});
    }

}

UserServiceImpl类我就不放上去了

测试代码:

package com.rl.spring.test;

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

import com.rl.spring.model.User;
import com.rl.spring.service.UserService;

@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:ApplicationContext.xml"})
public class TestSpring {
	
    @Autowired
    UserService userService;
    
    
    @Test
    public void test1() {
        User user = new User();
        user.setUserId(1);
        user.setUsername("zhangsan");
        user.setPassword("666");
        userService.updateUser(user);
    }
    
}

数据库结果:

接下来:

查询:

UserDaoImpl类:

package com.rl.spring.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.rl.spring.dao.UserDao;
import com.rl.spring.model.User;
import com.rl.spring.model.UserRowMapper;

public class UserDaoImpl implements UserDao {
    
    //需要引入数据源
    private DataSource dataSource;
    
    private JdbcTemplate jt;
    
    /**
     * 使用配置文件的方式注入必须提供set方法
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jt = new JdbcTemplate(dataSource);
    }

   

    @Override
    public User queryUserById(int userId) {
        String sql = "select * from t_user where user_id = ?";
        User user = jt.queryForObject(sql, new Object[] {userId}, new UserRowMapper());
        return user;
    }

    @Override
    public List<User> queryUserAll() {
        String sql = "select * from t_user";
        List<User> userList = jt.query(sql, new UserRowMapper());
        return userList;
    }
}

测试代码:

package com.rl.spring.test;

import java.util.List;

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

import com.rl.spring.model.User;
import com.rl.spring.service.UserService;

@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:ApplicationContext.xml"})
public class TestSpring {
	
    @Autowired
    UserService userService;
    
   
    
    @Test
    public void test2() {
        User user = userService.queryUserById(1);
        System.out.println(user);
    }
    
    @Test
    public void test3() {
        List<User> userList = userService.queryUserAll();
        System.out.println(userList);
    }
    
}

结果就不截图了...

 

Spring对属性文件的读取

属性文件:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring_10
uname=root
pword=root
initialSize=1
maxActive=5
maxIdle=2
minIdle=1

最终的配置文件

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

    <!-- 配置属性文件的位置 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    
        <!-- 采用${xxx}的形式读取属性文件中对应key的内容 -->
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${uname}"></property>
        <property name="password" value="${pword}"></property>
        <!-- 初始化连接数 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 最大连接数 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 最小空闲连接数 -->
        <property name="minIdle" value="${minIdle}"></property>
    </bean>
    
    <bean id="userDao" class="com.rl.spring.dao.impl.UserDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="userService" class="com.rl.spring.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>

 

galaxy 起源于07年的一个数据库导库项目,做一个增删改查的功能,只要几行代码就可以了,只要你会简单的sql语句,就能快速完成一个 功能,相比struts2和spring,着实方便多了. 如果觉得好用,就放弃ssh吧,加入到galaxy的阵营。 1. 完成一个用户管理功能? user.jsp ,这个页面用于新增,修改一个用户 <html> <head></head> <body> <% MyHashMap req = RequestUtil.getRequest(request); MyHashMap obj = new Query("select * from user where id ="+req.getInt("id")); %> <form action="regesiterAction.jsp" method="post"> 用户名<input name="username" value="<%=obj.getString("username")%>" /> 密码<input type="password" value="<%=obj.getString("password")%>" name="password" /> 手机号: <input name="telphone" value="<%=obj.getString("username")%>" /> <input type="hidden" name="action" value="saveorupdate" /> <input type="submit" value="提交" /> </form> </body> </html> userAction.jsp <% MyHashMap req = RequestUtil.getRequest(request); if(req.getString("action").equals("saveorupdate")){ new Imp().saveOrUpdate(req); }else if(req.getString("action").equals("del")){ new Query().update("delete from user where id="+req.getString("id")); } response.sendRededict("user.jsp"); %> 用户列表页面 <html> <body> <form> <table> <tr><td>用户名</td><td>密码</td><td>手机号</td> <% MyHashMap req = RequestUtil.getReq(request); int pagesize = req.getInt("pagesize",10); int pageindex = req.getInt("pageindex",1); List<MyHashMap> list = new Query().getByPaging("select * from user where "+condition,pagesize,pageindex); MyHashMap pageinfo = list.get(0); for(MyHashMap map:list){ %> <tr> <td><%=map.getString("username")%></td> <td><%=map.getString("password")%></td> <td><%=map.getString("telphone")%></td> </tr> <%}%> </table> <%=com.zxhy.fxpt.common.util.StringUtil.getdaohang(pageinfo.getInt("pagecount"),pageinfo.getInt("pagenum"))%> </form> </body> </html> 有兴趣的话,跟我联系qq: 376860997
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值