Spring框架基础(中)

时间:2021-05-18 05:11:13
  • Spring对不同持久化技术进行支持
    • JDBC
      • 导入spring-jdbc-4.3.5.RELEASE.jar、spring-tx-4.3.5.RELEASE.jar
      • 创建对象,设置数据库信息
      • 创建jdbcTemplate对象,设置数据源
      • 调用jdbcTemplate对象里面对方法实现操作
        public class TestDao {
        
              /**
        * 添加指定数据表的数据
        */
        public void insertUser() { try {
        //导入配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取参数
        String driver = properties.getProperty("jdbc.driver");
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        //
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setJdbcUrl(driver);
        driverManagerDataSource.setJdbcUrl(url);
        driverManagerDataSource.setUser(username);
        driverManagerDataSource.setPassword(password);
        //数据库语句
        String sql = "insert into user (username,password,email,root,register_time) values (?,?,?,?,?) ";
        //
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
        int rows = jdbcTemplate.update(sql,"rabbit","rabbit","rabbit@qq.com",1,"2019-3-2"); System.out.println("rows="+rows);
        } catch (IOException e) {
        e.printStackTrace();
        } } /**
        * 更新指定数据表的数据
        */
        public void updateUser() { try {
        //导入配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取参数
        String driver = properties.getProperty("jdbc.driver");
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        //
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setJdbcUrl(driver);
        driverManagerDataSource.setJdbcUrl(url);
        driverManagerDataSource.setUser(username);
        driverManagerDataSource.setPassword(password);
        //数据库语句 String sql = "update user set phone = ? where username = ?";
        //
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource); int rows = jdbcTemplate.update(sql,"13812392132","rabbit");
        System.out.println("rows=" + rows);
        } catch (IOException e) {
        e.printStackTrace();
        } }
        /**
        * 查询全部数据
        */
        public void selectAllUser() { try {
        //导入配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取参数
        String driver = properties.getProperty("jdbc.driver");
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        //
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setJdbcUrl(driver);
        driverManagerDataSource.setJdbcUrl(url);
        driverManagerDataSource.setUser(username);
        driverManagerDataSource.setPassword(password);
        //数据库语句 String sql = "select * from user";
        //
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource); List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        System.out.println("maps=" + maps);
        } catch (IOException e) {
        e.printStackTrace();
        } }
        /**
        * 删除指定数据
        */
        public void deleteUser() { try {
        //导入配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取参数
        String driver = properties.getProperty("jdbc.driver");
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        //
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setJdbcUrl(driver);
        driverManagerDataSource.setJdbcUrl(url);
        driverManagerDataSource.setUser(username);
        driverManagerDataSource.setPassword(password);
        //数据库语句 String sql = "delete from user where username = ?";
        //
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource); int row = jdbcTemplate.update(sql, "rabbit");
        System.out.println("row=" + row);
        } catch (IOException e) {
        e.printStackTrace();
        } } /**
        * 查询指定数据表的记录数
        */
        public void selectCountUser() {
        try {
        //导入配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取参数
        String driver = properties.getProperty("jdbc.driver");
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        //
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setJdbcUrl(driver);
        driverManagerDataSource.setJdbcUrl(url);
        driverManagerDataSource.setUser(username);
        driverManagerDataSource.setPassword(password);
        //数据库语句 String sql = "select count(*) from user";
        //
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
        //第一个参数sql语句,第二个参数返回的数据类型
        Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
        System.out.println("count=" + count);
        } catch (IOException e) {
        e.printStackTrace();
        } } public void selectUser();() { try {
        //导入配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        //获取参数
        String driver = properties.getProperty("jdbc.driver");
        String url = properties.getProperty("jdbc.url");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        //
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setJdbcUrl(driver);
        driverManagerDataSource.setJdbcUrl(url);
        driverManagerDataSource.setUser(username);
        driverManagerDataSource.setPassword(password);
        //数据库语句 String sql = "select * from user where username = ?"; User user = jdbcTemplate.queryForObject(sql, new NewRowMapper(), "rabbit");
        JSONObject jsonObject = JSONObject.fromObject(user);
        System.out.println(jsonObject + "");
        } catch (IOException e) {
        e.printStackTrace();
        } } /**
        * 处理查询结果集
        */
        class NewRowMapper implements RowMapper<User> { @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException { try {
        Class<?> newClass = Class.forName("cn.muriel.auto.pojo.User");
        Object o = newClass.newInstance();
        for (int j = 1; j <= resultSet.getMetaData().getColumnCount(); j++) {
        String name = resultSet.getMetaData().getColumnName(j);
        String type = resultSet.getMetaData().getColumnTypeName(j);
        //针对只有一次_的情况,多次则可用递归
        if (name.contains("_")) {
        int position = name.indexOf("_");
        String smailChar = name.substring(position + 1, position + 2).toUpperCase();
        name = name.substring(0, position) + smailChar + name.substring(position + 2, name.length());
        }
        Field declaredField = newClass.getDeclaredField(name);
        if (declaredField != null) {
        declaredField.setAccessible(true);
        if (type.equals("INT"))
        declaredField.set(o, resultSet.getInt(name));
        else if (type.equals("VARCHAR"))
        declaredField.set(o, resultSet.getString(name));
        } }
        return (User) o; } catch (ClassNotFoundException e) {
        e.printStackTrace();
        } catch (IllegalAccessException e) {
        e.printStackTrace();
        } catch (InstantiationException e) {
        e.printStackTrace();
        } catch (NoSuchFieldException e) {
        e.printStackTrace();
        } return null;
        }
        } } /**
        * 测试代码
        */
        public static void main(String[] args) { Test01 test01 = (Test01) applicationContext.getBean("test01");
        test01.test01();*/ TestDao dao = new TestDao();
        dao.insertUser();
        dao.updateUser();
        dao.selectAllUser();
        dao.selectUser();
        dao.selectCountUser();
        }
      • spring配置c3p0连接池
        • 导入mchange-commons-java-0.2.11.jar、c3p0-0.9.5.2.jar
        • 连接连接池
          • 代码实现
              InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            try {
            properties.load(inputStream);
            //获取参数
            String driver = properties.getProperty("jdbc.driver");
            String url = properties.getProperty("jdbc.url");
            String username = properties.getProperty("jdbc.username");
            String password = properties.getProperty("jdbc.password");
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass(driver);
            comboPooledDataSource.setJdbcUrl(url);
            comboPooledDataSource.setUser(username);
            comboPooledDataSource.setPassword(password);
            } catch (IOException e) {
            e.printStackTrace();
            } catch (PropertyVetoException e) {
            e.printStackTrace();
            }
          • 注入实现
            <?xml version="1.0" encoding="UTF-8" ?>
            <!--
            http://www.springframework.org/schema/context/spring-context.xsd:用于注解的约束
            -->
            <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:component-scan base-package="cn.muriel.auto.dao"/> --> <context:property-placeholder location="db.properties"/>
            <!-- 配置注入 -->
            <bean id="userDao" class="cn.muriel.auto.dao.UserDao"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"></property>
            <property name="jdbcUrl" value="${jdbc.url}"></property>
            <property name="user" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
            </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"/>
            </bean> <bean id="testDao" class="cn.muriel.auto.dao.TestDao">
            <property name="jdbcTemplate" ref="jdbcTemplate"/>
            </bean> </beans>
    • Hibernate
    • Ibatis(MyBatis)
    • JPA
  • Spring的事务管理
    • 什么是事务
    • 事务的特性
    • 不考虑隔离性产生读问题
    • 解决读问题
      • 设置隔离级别
    • spring事务管理两种方式
      • 编程式事务管理
      • 声明式事务管理
        • 基于xml配置文件实现
           <!-- 配置事务管理器 -->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <!-- 注入dataSource -->
          <property name="dataSource" ref="dataSource"/>
          </bean>
          <!-- 配置事务增强 -->
          <tx:advice id="txadvice" transaction-manager="transactionManager">
          <!-- 做事务操作 -->
          <tx:attributes>
          <!--
          设置进行事务操作的方法匹配规则
          name:匹配名字
          propagation:默认。
          -->
          <tx:method name="insert*" propagation="REQUIRED"/>
          </tx:attributes>
          </tx:advice>
          <!-- 配置切面 -->
          <aop:config>
          <!-- 切入点 -->
          <aop:pointcut id="pointcut1" expression="* (cn.muriel.auto.service.TestService.*)(..)"/>
          <!-- 切面 -->
          <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/>
          </aop:config>
        • 基于注解实现
            <!-- 配置事务管理器 -->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <!-- 注入dataSource -->
          <property name="dataSource" ref="dataSource"/>
          </bean>
          <!-- 配置事务注解 -->
          <tx:annotation-driven transaction-manager="transactionManager"/> /**
          * 使用事务的方法所在类上面添加注解
          */
          @Transactional
          public class TestService { }
    • spring事务管理高层抽象主要包括3个接口
      • PlatformTransactionManager(事务管理器)
        • spring针对不同的dao层框架,提供接口不同的实现类
        • 首先都要配置事务管理器
      • TransactionDefinition(事务定义信息(隔离、传播、超时、只读))
      • TransactionStatus(事务具体运行状态)