Spring基础

2017-07-31  本文已影响10人  stutterr
1. 引入
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:applicationContext.xml</param-value>
</context-param>

当前上下文配置文件目录是在src下

<listener>
   <display-name></display-name>
   <listener-class>org.spirngframework.web.context.ContextLoaderListener</listener-class>
</listener>

这个启动方法就会去解析我们的contextConfig文件。

2. 在util包下创建SpringUtil class

工厂模式引入

public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;
    @Override
    public void setApplicationContext(ApplicationContext ac)  //beanFactory 通过这个类可以取到配置文件的东西
            throws BeansException {
        applicationContext = null;
        
    }
    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    public static Object getBean(String beanId) {
        ApplicationContext applicationContext = getApplicationContext();
        return applicationContext.getBean(beanId);
    }
}

这边的ApplicationContext类相当于一个beanFactory.用来获取bean.xml中的配置。

3. Spring中的JdbcTemplate使用方法

initialPoolSize 初始化产生的数量
acquireIncrement 访问量增大时连接每次增大的数量
minPoolSize 最小数量
maxPoolSize 最大数量

*设置JDBCTemplate

   
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
       <property name="dataSource">
           <ref bean="dataSource" /> 
       </property>
   </bean>

之后在DAO中定义,并且设置set方法已供spring注入. 注意,导入的包应该在spring下

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

*使用

       String sql = "SELECT * FROM user WHERE user_name= ?";
       Object[] args = new Object[] {userName};  //准备参数
       
       //每行处理,rsToObject
       RowMapper<User> rowMapper = new RowMapper<User>() {

           @Override
           public User mapRow(ResultSet rs, int rowNum) throws SQLException {
               User user = new User();
               user.setId(rs.getInt(1));
               user.setUserName(rs.getString("user_name"));
               user.setPassword(rs.getString("password"));
               return user;
           }
       };
       return jdbcTemplate.queryForObject(sql, args, rowMapper);

注意事项,请确保每个注入类都有set方法和被注入类有无参数的构造函数。

查询基本结构

        String sql = "SELECT * FROM question WHERE id= ?";
        Object [] args = new Object[] {questionId};

        RowMapper<Question> rowMapper =new RowMapper<Question>(){
            @Override
            public Question mapRow(ResultSet rs, int rowNum)
                    throws SQLException {
                Question question = new Question();
                question = new Question();
                question.setId(rs.getInt(1));
                question.setDisplayId(rs.getString("display_id"));
                question.setDescription(rs.getString("description"));
                question.setQuestionOptionList(findQuestionOptionByQuestionId(questionId));
                return question;
            }
        };

        return jdbcTemplate.queryForObject(sql, args,rowMapper);

Object [] args放置查询参数
RowMapper 用来获取构建查询结果
queryForObject 返回一个实例,如果多条查询用query
插入update 删除excute(),

如何返回插入后返回主键id?

        final String sql = "Insert INTO question(display_id, description, created_time, updated_time)"+
                "VALUES(?, ?, NOW(), NOW())";
        KeyHolder keyHolder = new GeneratedKeyHolder();

        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con)
                    throws SQLException {
                PreparedStatement preState=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                preState.setString(1,question.getDisplayId());
                preState.setString(2,question.getDescription());
                return preState;
            }
        }, keyHolder);
        question.setId(keyHolder.getKey().intValue());

定义一个keyHolder 并且使用PreparedStatementCreator来获取自增ID。

4. 申明式事务配置
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource"></property>
   </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="saveQuestion" propagation="REQUIRED" read-only="false"/>
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

在被写上propagation="REQUIRED" read-only="false"会启动事务管理器
rollback-for 代表发生什么异常时回滚 。默认时runtimeException 所以我们要将一些exception都换成runtimeException

aop:advisor切面中加上通知。

    <aop:config>
       <aop:pointcut expression="execution(* com.gavin.exam.service..*.*(..))" id="pc"/>
       <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" order="1"/>
   </aop:config>
上一篇下一篇

猜你喜欢

热点阅读