zoukankan      html  css  js  c++  java
  • spring与Dbcp

    基于jdbc,操作数据库速度比较快,优于hibernate但是功能没hibernate强大,增删改可以用,查询用起来比较麻烦

    使用,首先jar包支持
    commons-pool.jar
    commons-dbcp.jar
    mysql-connector-java-5.1.12-bin.jar
    在之前的基础上加上spring-tx-4.2.0.RELEASE 这个包
    基础jar包


    这里要使用dbcp的话我们首先需要做的是配置spring的dataSource 同样的这也是我们以后要使用数据库主要的核心
    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/emp" />
    <property name="username" value="root" />
    <property name="password" value="admin"/>
    <property name="maxActive" value="10"></property>
    <property name="initialSize" value="2"></property>
    <property name="minIdle" value="2"></property>
    <property name="maxIdle" value="3"></property>
    </bean>
    解释:
    <property name="maxActive" value="10"></property> 连接池中最多10个链接
    <property name="initialSize" value="2"></property> 池子创建好后一开始就有2个链接
    <property name="minIdle" value="2"></property> 最小空闲数
    <property name="maxIdle" value="3"></property>最大空闲数

    配置好了之后我们就可以正常使用了,在类中要使用我们首先要见过这个dbcp注入到类中去
    完成注入:
    <bean name="userDaoImpl" class="com.spring.dbcp.UserDaoImpl">
    <property name="dataSource" ref="dataSource"></property>
    </bean> 

    然后需要让你的类继承JdbcDaoSupport这个类就可以了(最简单的方式)
    public class UserDaoImpl extends JdbcDaoSupport

    最后this.getJdbcTemplate()--获得jdbc模板就可以了

    不过这里很麻烦,因为要继承类,我们有一种不需要继承的写法
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
    </bean>

    然后在我们的类中
    @Resource
    private JdbcTemplate template;
    这样就能获得了
    案例:
    演示增删改的操作

    注意这个我们用的这个函数函数的有两个常用的参数update(sql,new Object[]{})----注意第一个参数是sql语句,如果有参数用占位符,第二个参数为设置占位符参数的位置


    那我们的查询呢?
    除了这个方法我们还有
    queryForObject(sql,new UserMapper());---查处一个对象放在一个OBJECT中
    queryForList(sql)---返回list数组对象

    query(sql,rowMappwe)--查询结果集

    queryForInt(sql);--查询聚合函数


    这里比较麻烦的是查询这个东西,因为它首先需要的是一个映射表
    public class UserMapper implements RowMapper

    public Object mapRow(ResultSet rs, int index) throws SQLException {
    User user=new User();
    user.setId(rs.getInt("id"));
    user.setEmail(rs.getString("email"));
    user.setNickName(rs.getString("nickname"));
    if(rs.getString("is_email_verify").equals("Y")){
    user.setEmailVerify(true);
    }else{
    user.setEmailVerify(false);
    }
    user.setEmailVerifyCode(rs.getString("email_verify_code"));
    user.setLastLoginIp(rs.getString("last_login_time"));
    return user;
    }


    注意这里Spring2.5开始新增了一个类BeanPropertyRowMapper

    我们可以这么玩
    public List<User> findAll() {
    String sql="select * from d_user";
    return (List<User>) this.getJdbcTemplate().query(sql,new BeanPropertyRowMapper(User.class));---这里
    }

    我们就不用那么麻烦的去做一对mapper了

    想一想它的好处坏处都有啥

    配置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"
        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.0.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">
        <context:component-scan base-package="com.wode">
        </context:component-scan> 
        <bean id="dataSource" destroy-method="close"
            class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/test" />
            <property name="username" value="root" />
            <property name="password" value="lovo" />
            <property name="maxActive" value="10"></property>
            <property name="initialSize" value="2"></property>
            <property name="minIdle" value="2"></property>
            <property name="maxIdle" value="3"></property>
        </bean>
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource" />
        </bean>
        
    
    </beans>

    在dao层:

    @Repository
    public class UserDaoImpl implements UserDao{
        @Resource
        private JdbcTemplate jdbcTemplate;
    
        
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
        
        /**
         * 增加用户
         */
        @Override
        public int addUser(User user) {
            String sql="INSERT INTO users VALUES(null,?,?)";
            int result=jdbcTemplate.update(sql, new Object[]{user.getUserName(),user.getUserPwd()});
            return result;
        }
        
        /**
         * 删除用户
         */
        @Override
        public int delUserById(int id) {
            String sql="DELETE FROM users WHERE USER_id=?";
            int result=jdbcTemplate.update(sql, new Object[]{id});
            return result;
        }
    
        /**
         * 修改用户
         */
        @Override
        public int updateUserById(int id,User user) {
            String sql="UPDATE users SET user_name=?,user_pwd=? WHERE user_id=?";
            int result=jdbcTemplate.update(sql, new Object[]{user.getUserName(),user.getUserPwd(),id});
            return result;
        }
    
        /**
         * 查看用户
         */
        @Override
        public User selectUserById(int id) {
            String sql="select * from users where user_id=?";
            User user=jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
         return user;
        }
    
    
    
    }

    然后:

    AbstractApplicationContext  atx=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService  userService=(UserService) atx.getBean("userServiceImpl");

    通过类似userService.updateUserById(user)的方法实现增删改查

  • 相关阅读:
    取得窗口大小和窗口位置兼容所有浏览器的js代码
    一个简单易用的导出Excel类
    如何快速启动chrome插件
    网页表单设计案例
    Ubuntu下的打包解包
    The source file is different from when the module was built. Would you like the debugger to use it anyway?
    FFisher分布
    kalman filter
    Group delay Matlab simulate
    24位位图格式解析
  • 原文地址:https://www.cnblogs.com/xieshunjin/p/5797647.html
Copyright © 2011-2022 走看看