014. Spring JdbcDaoSupport访问数据库

来源:互联网 发布:java获取进程端口号 编辑:程序博客网 时间:2024/06/05 03:10

1、创建Java项目:File -> New -> Java Project

2、项目结构
这里写图片描述

3、必要jar包
这里写图片描述

4、创建数据库,使用MySQL数据库

SET NAMES GBK;CREATE DATABASE IF NOT EXISTS `db_spring`;USE `db_spring`;DROP TABLE IF EXISTS `tb_user`;CREATE TABLE `tb_user`(    `id` INTEGER PRIMARY KEY NOT NULL,    `name` VARCHAR(16) NOT NULL,    `pswd` VARCHAR(32) NOT NULL)ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `tb_user`(`id`, `name`, `pswd`) VALUES(146, '吴腾辉', '105032014146'), (148, '吴钟灯', '105032014148');

5、创建UserModel实体类UserModel.java

package com.spring.model;public class UserModel {    private int id;    private String name;    private String pswd;    public UserModel() {        super();    }    public UserModel(int id, String name, String pswd) {        super();        this.id = id;        this.name = name;        this.pswd = pswd;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPswd() {        return pswd;    }    public void setPswd(String pswd) {        this.pswd = pswd;    }    @Override    public String toString() {        return "UserModel [id=" + id + ", name=" + name + ", pswd=" + pswd + "]";    }}

6、创建UserDao接口UserDao.java

package com.spring.dao;import java.util.List;import com.spring.model.UserModel;public interface UserDao {    public UserModel getUser(int id);    public List<UserModel> getUsers();    public int insertUser(UserModel user);    public int updateUser(UserModel user);    public int deleteUser(int id);}

7、创建UserDaoImp实现类UserDaoImp.java

package com.spring.dao.imp;import java.sql.ResultSet;import java.sql.SQLException;import java.util.LinkedList;import java.util.List;import org.springframework.jdbc.core.RowCallbackHandler;import org.springframework.jdbc.core.support.JdbcDaoSupport;import com.spring.dao.UserDao;import com.spring.model.UserModel;public class UserDaoImp extends JdbcDaoSupport implements UserDao{    @Override    public UserModel getUser(int id) {        String sql = "select id, name, pswd from tb_user where id=?";        UserModel user = new UserModel();        this.getJdbcTemplate().query(sql, new RowCallbackHandler(){            @Override            public void processRow(ResultSet rs) throws SQLException {                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPswd(rs.getString("pswd"));            }        }, id);        return user;    }    @Override    public List<UserModel> getUsers() {        List<UserModel> userList = new LinkedList<UserModel>();        String sql = "select id, name, pswd from tb_user";        this.getJdbcTemplate().query(sql, new RowCallbackHandler(){            UserModel user = null;            @Override            public void processRow(ResultSet rs) throws SQLException {                user = new UserModel();                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPswd(rs.getString("pswd"));                userList.add(user);            }        });        return userList;    }    @Override    public int insertUser(UserModel user) {        String sql = "insert into tb_user(id, name, pswd) values(?,?,?)";        Object params[] = new Object[]{user.getId(), user.getName(), user.getPswd()};        return this.getJdbcTemplate().update(sql, params);    }    @Override    public int updateUser(UserModel user) {        String sql = "update tb_user set name=?, pswd=? where id=?";        return this.getJdbcTemplate().update(sql, user.getName(), user.getPswd(), user.getId());    }    @Override    public int deleteUser(int id) {        String sql = "delete from tb_user where id=?";        return this.getJdbcTemplate().update(sql, id);    }}

8、创建UserService接口UserService.java

package com.spring.service;import java.util.List;import com.spring.model.UserModel;public interface UserService {    public UserModel getUser(int id);    public List<UserModel> getUsers();    public int insertUser(UserModel user);    public int updateUser(UserModel user);    public int deleteUser(int id);}

9、创建UserServiceImp实现类UserServiceImp.java

package com.spring.service.imp;import java.util.List;import com.spring.dao.UserDao;import com.spring.model.UserModel;import com.spring.service.UserService;public class UserServiceImp implements UserService {    private UserDao userDao;    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }    @Override    public UserModel getUser(int id) {        return userDao.getUser(id);    }    @Override    public List<UserModel> getUsers() {        return userDao.getUsers();    }    @Override    public int insertUser(UserModel user) {        return userDao.insertUser(user);    }    @Override    public int updateUser(UserModel user) {        return userDao.updateUser(user);    }    @Override    public int deleteUser(int id) {        return userDao.deleteUser(id);    }}

10、创建数据库配置文件jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/db_springjdbc.username=rootjdbc.password=

11、创建spring配置文件applicationContext.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"       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="jdbc.properties"/>    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">        <property name="driverClassName" value="${jdbc.driverClassName}"/>        <property name="url" value="${jdbc.url}"/>        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>    </bean>    <bean id="userDao" class="com.spring.dao.imp.UserDaoImp">        <property name="dataSource" ref="dataSource"></property>    </bean>    <bean id="userService" class="com.spring.service.imp.UserServiceImp">        <property name="userDao" ref="userDao"></property>    </bean></beans>

12、创建Spring测试类SpringUnit.java

package com.spring.junit;import java.util.List;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.model.UserModel;import com.spring.service.UserService;public class SpringUnit {    private ClassPathXmlApplicationContext ctx = null;    private UserService userService = null;    @Before    public void setUp() throws Exception {        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");        userService = (UserService) ctx.getBean("userService");    }    @After    public void tearDown() throws Exception {        ctx.close();    }    @Test    public void test() {        testInsert();        testUpdate();        testDelete();        testGetUsers();    }    private void testInsert() {        userService.insertUser(new UserModel(147, "吴志祥", "105032014140"));        System.out.println(userService.getUser(147).toString());    }    private void testUpdate() {        userService.updateUser(new UserModel(147, "吴志祥", "105032014147"));        System.out.println(userService.getUser(147).toString());    }    private void testDelete() {        userService.deleteUser(147);        System.out.println(userService.getUser(147).toString());    }    private void testGetUsers() {        List<UserModel> userList = userService.getUsers();        for(UserModel user: userList) {            System.out.println(user.toString());        }    }}

13、测试结果

... 省略Spring日志信息 ...UserModel [id=147, name=吴志祥, pswd=105032014140]UserModel [id=147, name=吴志祥, pswd=105032014147]UserModel [id=0, name=null, pswd=null]UserModel [id=146, name=吴腾辉, pswd=105032014146]UserModel [id=148, name=吴钟灯, pswd=105032014148]... 省略Spring日志信息 ...
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 全血粘度值1偏高怎么办 全血粘度3偏高怎么办 血粘度高的症状怎么办 粉瘤感染化脓了怎么办 乌药剂量用大了怎么办 水卡消磁了怎么办妙招 电卡消磁了怎么办妙招 入园磁卡消磁了怎么办 透析中静脉压高怎么办 腰间盘突出压迫神经腿疼怎么办 肺热引起的发烧怎么办 肺热引起的痘痘怎么办 冰箱压条的霉点怎么办 白色的布鞋变黄怎么办 白鞋橡胶变黄了怎么办 肝功能检查总胆汁酸高怎么办 吃丹参滴丸尿血怎么办 胰酶消化过久怎么办 抗凝血酶活性低怎么办 抗凝血酶3偏低怎么办 抗凝血酶ⅲ低 怎么办 抗凝血酶3抗原高怎么办 孕32周血压高怎么办 智齿血凝块掉了怎么办 入职体检alt偏高怎么办 剖腹产后crp值高怎么办 超敏c反应蛋白偏高怎么办 孕妇c反应蛋白高怎么办 婴儿超敏crp偏高怎么办 小孩c反应蛋白高怎么办 发烧c反应蛋白高怎么办 孕妇快生了贫血怎么办 小孩吃糖牙齿痛怎么办 前门牙掉了一块怎么办 吃冷东西牙疼怎么办 吃甜的立刻牙疼怎么办 吃甜的牙疼怎么办 孕妇甲功t4偏低怎么办 得了肝内钙化灶怎么办 喝了除垢剂的水怎么办 喝甘露醇后吐了怎么办