zoukankan      html  css  js  c++  java
  • spring-第三章-jdbc

    一,回顾

    aop:面向切面编程,就是将一些和主业务流程没有关系的公共代码,提取封装到切面类,通过切入点规则,可以对目标方法进行功能增强;也就是可以再目标方法执行的前后添加一段额外逻辑代码;

    二,JdbcTemplate模板类

    spring框架对数据库的操作在jdbc基础上做了封装,使用spring依赖注入功能,可以吧DataSource(数据源,链接地址,账号,密码,驱动类)注入给JdbcTemplate模板类中,然后就可以使用JdbcTemplate工具类对数据表进行增删改查操作

    1、数据库和表

    create table userInfo(
        id int not null primary key auto_increment,
        no char(4) not null unique,
        name varchar(20) not null,
        pwd varchar(20) not null,
        sex int not null,
        age int not null
    )
    insert into userInfo values(0,'U001','小明','123456',1,20);
    insert into userInfo values(0,'U002','小红','123456',0,18);
    insert into userInfo values(0,'U003','小方','123456',1,21);

    2、添加依赖

    <!-- spring-context -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.1.0.RELEASE</version>
            </dependency>
            <!-- spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.1.0.RELEASE</version>
            </dependency>
            <!-- spring-tx -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>5.1.0.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.2</version>
                <scope>provided</scope>
            </dependency>
    <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>

    3、配置数据源DataSource

    (1)在src目录中新建jdbc.properties配置文件

    jdbc.url=jdbc:mysql://127.0.0.1:3306/spring-test?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=123456

    (2)在spring.xml中引用资源配置文件

    <!-- 引用配置文件 -->
        <context:property-placeholder location="classpath:jdbc.properties"/>

    (3)在spring.xml中配置数据源以及使用配置文件中的key

    <!-- 数据源配置 :配置连接地址、账号、密码;下面的url、username、password属性来自于DriverManagerDataSource的父类AbstractDriverBasedDataSource-->
        <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>

    4、注册JdbcTemlate模板工具类

    在spring.xml中配置工具类

    <!-- 注册jdbcTemplate工具类实例    dataSource属性就是数据源-->
        <bean id="jdbcTemplate1" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource1"></property>
        </bean>

    5、UserInfo实体类

    @Data
    public class UserInfo {
        private Integer id;
        private String no;
        private String name;
        private String pwd;
        private Integer sex;
        private Integer age;
    }

    6、UserInfoDao接口

    public interface UserInfoDao {
        //添加
        void add(UserInfo user);
    }

    7、UserInfoDaoImpl实现类

    @Data
    public class UserInfoDaoImpl implements UserInfoDao {
    
        //工具类
        private JdbcTemplate jdbcTemplate;
        
        @Override
        public void add(UserInfo user) {
            //update()可以执行增删改,后面的参数可以可变类型,依次为SQL语句中的?赋值
            String sql = "insert into userInfo values(0,?,?,?,?,?)";
            jdbcTemplate.update(sql, user.getNo(),user.getName(),user.getPwd(),user.getSex(),user.getAge());
        }
    
    }

    这里的jdbcTemplate属性,必须有set和get方法,否则spring不能正常给它注入实例

    8、注册UserInfoDaoImpl实例

    在spring.xml中注册

    <bean id="userInfoDaoImpl" class="com.yujun.maven.dao.impl.UserInfoDaoImpl">
            <property name="jdbcTemplate" ref="jdbcTemplate1"></property>
    </bean>

    注意的是需要给UserInfoDaoImpl类注入jdbcTemlate的实例

    9、添加

    public class Demo1 {
    
        public static void main(String[] args) {
            //context上下文对象(spring容器)
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
            
            
            UserInfo user = new UserInfo();
            user.setAge(20);
            user.setName("明明");
            user.setNo("U004");
            user.setPwd("123456");
            user.setSex(0);
            
            dao.add(user);
            System.out.println("over...");
        }
    
    }

    10、修改

    (1)UserInfoDao接口中添加方法

    //修改
        void update(UserInfo user);

    (2)UserInfoDaoImpl实现类中重写方法

    @Override
        public void update(UserInfo user) {
            String sql = "update userinfo set no=?,name=?,pwd=?,sex=?,age=? where id=?";
            jdbcTemplate.update(sql, user.getNo(),user.getName(),user.getPwd(),user.getSex(),user.getAge(),user.getId());
        }

    (3)测试

    public static void main(String[] args) {
            //context上下文对象(spring容器)
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
            
            UserInfo user = new UserInfo();
            user.setId(5);
            user.setAge(22);
            user.setName("明明5");
            user.setNo("U005");
            user.setPwd("654321");
            user.setSex(1);
            
            dao.update(user);
            System.out.println("over...");
        }

    11、删除

    (1)UserInfoDao接口中添加方法

    //删除
        void delete(Integer id);

    (2)UserInfoDaoImpl实现类中重写方法

    @Override
        public void delete(Integer id) {
            String sql = "delete from userInfo where id=?";
            jdbcTemplate.update(sql, id);
        }

    (3)测试

    public static void main(String[] args) {
            //context上下文对象(spring容器)
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
            
            dao.delete(5);
            System.out.println("over...");
        }

    三、JdbcTemplate模板类-查询

    1、查询单个结果

    查询userinfo表中的记录数(count(*))

    (1)UserInfoDao接口添加方法

    //查询count(*)
        int queryCount();

    (2)UserInfoDaoImpl实现类重写方法

    @Override
        public int queryCount() {
            String sql = "select count(*) from userInfo";
            Integer count = jdbcTemplate.queryForObject(sql, int.class);
            return count;
        }

    (3)测试

    public static void main(String[] args) {
            //context上下文对象(spring容器)
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
            
            int count = dao.queryCount();
            System.out.println("总记录数:"+count);
            System.out.println("over...");
        }

    2、查询单一实体对象

    根据用户的ID查询出唯一的用户实体数据

    (1)UserInfoDao接口添加方法

    //根据ID查询唯一数据
        UserInfo queryById(Integer id);

    (2)UserInfoDaoImpl实现类重写方法

    @Override
        public UserInfo queryById(Integer id) {
            String sql = "select * from userInfo where id=?";
            return jdbcTemplate.queryForObject(sql, new RowMapper<UserInfo>() {
                //RowMapper是行映射器,需要再mapRow()方法中对每行数据进行映射
                @Override
                public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                    String no = rs.getString("no");
                    String name = rs.getString("name");
                    String pwd = rs.getString("pwd");
                    Integer sex = rs.getInt("sex");
                    Integer age = rs.getInt("age");
                    UserInfo user = new UserInfo(id, no, name, pwd, sex, age);
                    return user;
                }
            }, id);
        }

    (3)测试

    public static void main(String[] args) {
            //context上下文对象(spring容器)
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
            
            UserInfo info = dao.queryById(1);
            System.out.println(info);
            
            System.out.println("over...");
        }

    3、查询集合对象

    (1)UserInfoDao接口添加方法

    //根据sex查询数据集合
        List<UserInfo> queryBySex(int sex);

    (2)UserInfoDaoImpl实现类重写方法

    @Override
        public List<UserInfo> queryBySex(int sex) {
            String sql = "select * from userInfo where sex=?";
            return jdbcTemplate.query(sql, new RowMapper<UserInfo>() {
                //RowMapper是行映射器,需要再mapRow()方法中对每行数据进行映射
                @Override
                public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                    int id = rs.getInt("id");
                    String no = rs.getString("no");
                    String name = rs.getString("name");
                    String pwd = rs.getString("pwd");
                    Integer sex = rs.getInt("sex");
                    Integer age = rs.getInt("age");
                    UserInfo user = new UserInfo(id, no, name, pwd, sex, age);
                    return user;
                }
            }, sex);
        }

    这里的映射器写法和前面查询单一实体对象一样

    (3)测试

    public static void main(String[] args) {
            //context上下文对象(spring容器)
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
            
            List<UserInfo> list = dao.queryBySex(0);
            list.forEach(System.out::println);
            
            System.out.println("over...");
        }

    四、补充说明

             上面我们使用JdbcTemplate模板工具类完成后简单的增删改查操作,更多详细的操作可以查看官方文档或百度;

             在上面的案例中,有2个问题需要被完善:

    (1)       数据源没有使用连接池技术

    (2)       数据源没有事务的支持

    关于上述两个问题,我们会在下次课spring+hibernate中一起完善;

  • 相关阅读:
    @SerializedName注解
    信号量与互斥锁
    MySQL分配角色权限
    PO、VO、DAO、BO、POJO
    Java工程为什么要加一个biz层
    Java学习之强引用,弱引用,软引用 与 JVM
    深入Activity,Activity启动模式LaunchMode完全解析
    活体检测
    遥感图像数据集
    NNIE(待尝试)
  • 原文地址:https://www.cnblogs.com/faded8679/p/10797122.html
Copyright © 2011-2022 走看看