`

spring与jdbc注解形式

    博客分类:
  • java
 
阅读更多
Spring与JDBC 

2011-05-16 21:54:18|  分类: spring |  标签:spring  jdbc  总结  大全   |字号 订阅
JDBC是java部分连接数据库的基础,来我的博客对他进行复习吧,下面是对jdbc的一些知识点总结。
1.配置文件
我们需要在配置文件中配置数据源,数据源的配置格式大致如下:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/student"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
  </bean>
当然我们还可以配置其他的比方说连接池信息:
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="100"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="100"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="100"/>
<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="100"/>
我们在实际应用中经常需要将相应的信息写到一个文件中,如果需要修改直接修改这个文件即可,下面我列出方法
1)创建jdbc.properties文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test
username=root
password=root
2)在配置文件中引用
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${driverClassName}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
  </bean>
注意在location中加入classpath,代表使用的是web应用的伪路径。在value中我们像EL
表达式一样去获取即可。
2.JDBC的使用
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
}
解释一下上面的代码,@Resource是注入dataSource,如果不带参数按类型匹配,这个不用多说了,在set方法中new出jdbcTemplate.
3.利用jdbcTemplate进行相应的数据操作
public List<Person> getAllPerson() {//查询list
List list=jdbcTemplate.queryForList("select * from employee");//如果要有条件查询,可以用jdbcTemplate.queryForList(sql, args, argTypes)
return list;
}
public Person getPerson(Integer empid) {//查询object
Person person=(Person)jdbcTemplate.queryForObject("select * from employee where empid=?",new Object[]{empid},
new RowMapper(){
public Object mapRow(ResultSet rs, int index) throws SQLException {
Person person=new Person();
person.setEmpid(rs.getInt("empid"));
person.setEmpname(rs.getString("empname"));
person.setDepartid(rs.getInt("departid"));
return person;
}
}
);
return person;
}
public void save(Person person) {//插入
jdbcTemplate.update("insert into employee(empname,departid) values(?,?)",new Object[]{person.getEmpname(),person.getDepartid()}
,new int[]{Types.VARCHAR,Types.INTEGER}
);
}
public void update(Person person) {//更新
jdbcTemplate.update("update employee set empname=? where empid=?",new Object[]{person.getEmpname(),person.getEmpid()},
new int[]{Types.VARCHAR,Types.INTEGER});
}
4.事务管理
在我们上面的程序中,我们发现我们并没有对事务进行管理,实际上我们是使用了JdbcTemplate的事务管理,在实际开发中,我们需要将事务交给spring来管理,下面是一些总结:
1)配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
</beans>
首先引入tx命名空间,上面的红色部分文字。同样还要加入下面的语句:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="dataSource"/><!--dataSource为数据源配置的id-->
  </bean>
  <tx:annotation-driven transaction-manager="txManager"/>
2)jdbc类
@Transactional  //将事务交给spring容器管理,spring在方法结束前打开事务,方法结束后关闭事务
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void deletePerson(Integer empid) {
jdbcTemplate.update("delete from employee where empid=?",new Object[]{empid}
,new int[]{Types.INTEGER}
);
}
}
在类得上面加入@Transactional来定义将此类的事务交给spring来管理,加上这个注解后就默认为每个方法加上了spring的事务管理,在方法开始的时候打开事务,在方法结束的时候关闭事务。
很多查询的方法是没有进行事务管理的,如果加上事务管理还会降低效率,此时我们需要在方法的上面配置注解:
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public List<Person> getAllPerson() {
List list=jdbcTemplate.queryForList("select * from employee");
return list;
}
说到了propagation ,我就谈谈propagation的几个属性:
A.REQUIRED
他是我们最常用的传播属性,也是默认值(方法上不进行修改就默认为他),业务方法需要在一个事务中运行。如果方法运行时,已经处在一个事务中,那么加入到该事务,否则为自己创建一个新的事务。
B.NOT_SUPPORTED
声明方法不需要事务。如果方法没有关联到一个事务,容器不会为它开启事务。如果方法在一个事务中被调用,该事务会被挂起,在方法调用结束后,原先的事务便会恢复执行。
C.REQUIRESNEW
属性表明不管是否存在事务,业务方法总会为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务会被挂起,新的事务会被创建,直到方法执行结束,新事务才算结束,原先的事务才会恢复执行。
D.MANDATORY
该属性指定业务方法只能在一个已经存在的事务中执行,业务方法不能发起自己的事务。如果业务方法在没有事务的环境下调用,容器就会抛出例外。
E.SUPPORTS
这一事务属性表明,如果业务方法在某个事务范围内被调用,则方法成为该事务的一部分。如果业务方法在事务范围外被调用,则方法在没有事务的环境下执行。
F.Never
指定业务方法绝对不能在事务范围内执行。如果业务方法在某个事务中执行,容器会抛出例外,只有业务方法没有关联到任何事务,才能正常执行。
G.NESTED
如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按REQUIRED属性执行.它使用了一个单独的事务, 这个事务拥有多个可以回滚的保存点。内部事务的回滚不会对外部事务造成影响。它只对DataSourceTransactionManager事务管理器起效。下面是他的实现机理:
Connection conn = null;
try {
    conn.setAutoCommit(false);
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("update person set name='888' where id=1");//语句一
    Savepoint savepoint = conn.setSavepoint();
    try{  
            conn.createStatement().executeUpdate("update person set name='222' where sid=2");//语句二
    }catch(Exception ex){
            conn.rollback(savepoint);   
     }
      stmt.executeUpdate("delete from person where id=9");//语句三
      conn.commit();
       stmt.close();
    } catch (Exception e) {
         conn.rollback();
     }finally{
               try {
    if(null!=conn && !conn.isClosed()) conn.close();
                } catch (SQLException e) { e.printStackTrace(); }
     }
}
从上面的机理我们可以看出,如果语句二执行失败,他不会被保存到数据库中,但是语句一和三会保存到数据中,但是如果语句一或者三有一个执行失败,就不会保存在数据库中。什么意思了?也就是这适用于我们的一种请求,某一个业务逻辑他的执行成功与否不能影响我们的业务逻辑(语句二执行成功与否不会影响到语句一和三)。
3)如果执行失败了?会不会rollback?
做到这里我们又情不自禁的想到一个问题,如果上面的某一个方法在执行过程中出现异常了?会不会rollback?答案是如果我们得异常是未检查异常,他会rollback,如果是已检查异常,他不会rollback。
那么如何修改默认的回本条件了?
修改在普通异常时也进行rollback
@Transactional(rollbackFor=Exception.class)
修改在运行时异常时不进行rollback
@Transactional(noRollbackFor=RuntimeException.class)
5.最后简单介绍一下基于配置文件的事务管理:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
</bean>
<aop:config>
   <aop:pointcut id="transactionPointcut" expression="execution(* service..*.*(..))"/>
   <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
  <tx:attributes>
    <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
    <tx:method name="*"/>
  </tx:attributes>
</tx:advice>
解释一下代码的意思,首先是实例化一个事务的bean,接着配置要拦截的类型等,然后配置以get开始的方法为之读事务,其他方法采用默认配置。
6.JdbcTemplate的使用
在上面我简单介绍了下JdbcTemplate的常用方法的使用,下面我进行细化。
1)查询一个对象之queryForObject
在上面我查询对象时使用的是queryForObject 方法,这个方法的第三个参数中是个匿名函数,函数中将查询出的结果一一放进我们得bean中。其实在spring中有更简单的封装类替我们完成了这个功能。如下:
Person person=(Person)jdbcTemplate.queryForObject("select * from employee where empid=?", new Object[]{empid}, new BeanPropertyRowMapper(Person.class));
return person;
利用 new BeanPropertyRowMapper(Person.class)方法,他就替我们完成了填充的功能。
这个时候我们需要思考一下,他是怎么识别到的?我没有做实验,我觉得也没有做实验的必要,因为根据规范bean中的属性名和数据库中的字段名是一样的,一样还愁他找不到?如果你想没事找事就别把他们起的一样。
当然,我们在数据库中很多时候喜欢这样的字段:t_name,t_age,如果是这样的字段我们在bean中不会也要带下划线吧?当然不会,很可能我们在数据库中的字段名就叫tname,tage.
这个时候为了确保万无一失,应该怎么做了?这个时候可以用别名:
Select t_name as tname,t_age as age from user
2)查询多个对象之query
要查询的条件中包含多个结果时,需要用到query,当然是用也同上面。
person=(Person)jdbcTemplate.query("select * from employee",new BeanPropertyRowMapper(Person.class));
由于没有参数,所以用了没有数组的那个方法。
3)查询单个属性int之queryForInt
如果要查询的属性为int,那么可以用queryForInt方法。
String sql="select count(*) from employee";
int count=jdbcTemplate.queryForInt(sql);
4)查询单个属性之queryForObject
如果要查询单个属性,并且不是int,这个时候可以借用queryForObject来转型。
public String getName(int empid) {
String sql="select empname from employee where empid=?";
Object obj=jdbcTemplate.queryForObject(sql, new Object[]{empid}, new int[]{Types.INTEGER},String.class);
return (String)obj;
}
5)没有bean的时候可以用queryForMap查询单组数据
返回的是一个map,map中对应的是相应的字段名和值,当我们没有bean时可以用这个方法
6)没有bean时可以用queryForList查询多组数据
返回的是一个List,list中放的是map
7)增删改之update方法
public void save(Person person) {
jdbcTemplate.update("insert into employee(empname,departid) values(?,?)",new Object[]{person.getEmpname(),person.getDepartid()}
,new int[]{Types.VARCHAR,Types.INTEGER}
);
}
8)命名空间的使用
public User findUser(User user) {
String sql = "select id, name, money, birthday  from user "
+ "where money > :m and id < :id";
Map params = new HashMap();
params.put("m", user.getMoney());
params.put("id", user.getId());
Object u = named.queryForObject(sql, params, new BeanPropertyRowMapper(
User.class));
return (User) u;
}
在map中填值,进行转换
public User findUser1(User user) {
String sql = "select id, name, money, birthday  from user "
+ "where money > :money and id < :id";
SqlParameterSource ps = new BeanPropertySqlParameterSource(user);
Object u = named.queryForObject(sql, ps, new BeanPropertyRowMapper(
User.class));
return (User) u;
}
分享到:
评论

相关推荐

    spring-jdbc-5.3.15-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.3.15.jar; 赠送原API文档:spring-jdbc-5.3.15-javadoc.jar; 赠送源代码:spring-jdbc-5.3.15-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.3.15.pom; 包含翻译后的API文档:...

    SpringJDBC注解事务.zip

    SpringJDBC注解事务.zip,SpringJDBC注解事务.zip

    spring-jdbc-5.2.0.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.2.0.RELEASE.jar; 赠送原API文档:spring-jdbc-5.2.0.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.2.0.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.2.0.RELEASE....

    spring-jdbc-5.3.10-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.3.10.jar; 赠送原API文档:spring-jdbc-5.3.10-javadoc.jar; 赠送源代码:spring-jdbc-5.3.10-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.3.10.pom; 包含翻译后的API文档:...

    spring-jdbc-5.0.8.RELEASE-API文档-中英对照版.zip

    赠送jar包:spring-jdbc-5.0.8.RELEASE.jar; 赠送原API文档:spring-jdbc-5.0.8.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.0.8.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.0.8.RELEASE....

    spring-jdbc-5.3.7-API文档-中英对照版.zip

    赠送jar包:spring-jdbc-5.3.7.jar; 赠送原API文档:spring-jdbc-5.3.7-javadoc.jar; 赠送源代码:spring-jdbc-5.3.7-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.3.7.pom; 包含翻译后的API文档:spring...

    spring-jdbc-5.3.7-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.3.7.jar; 赠送原API文档:spring-jdbc-5.3.7-javadoc.jar; 赠送源代码:spring-jdbc-5.3.7-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.3.7.pom; 包含翻译后的API文档:spring...

    spring-jdbc-5.2.7.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.2.7.RELEASE.jar; 赠送原API文档:spring-jdbc-5.2.7.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.2.7.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.2.7.RELEASE....

    spring-jdbc-5.3.15-API文档-中英对照版.zip

    赠送jar包:spring-jdbc-5.3.15.jar 赠送原API文档:spring-jdbc-5.3.15-javadoc.jar 赠送源代码:spring-jdbc-5.3.15-sources.jar 包含翻译后的API文档:spring-jdbc-5.3.15-javadoc-API文档-中文(简体)-英语-...

    spring-jdbc-5.1.3.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.1.3.RELEASE.jar; 赠送原API文档:spring-jdbc-5.1.3.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.1.3.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.1.3.RELEASE....

    spring-jdbc-5.0.10.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.0.10.RELEASE.jar; 赠送原API文档:spring-jdbc-5.0.10.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.0.10.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.0.10....

    spring-jdbc-4.3.20.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-4.3.20.RELEASE.jar; 赠送原API文档:spring-jdbc-4.3.20.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-4.3.20.RELEASE-sources.jar; 包含翻译后的API文档:spring-jdbc-4.3.20....

    spring-jdbc-4.3.20.RELEASE-API文档-中英对照版.zip

    赠送jar包:spring-jdbc-4.3.20.RELEASE.jar 赠送原API文档:spring-jdbc-4.3.20.RELEASE-javadoc.jar 赠送源代码:spring-jdbc-4.3.20.RELEASE-sources.jar 包含翻译后的API文档:spring-jdbc-4.3.20.RELEASE-...

    spring-jdbc-4.2.2.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-4.2.2.RELEASE.jar; 赠送原API文档:spring-jdbc-4.2.2.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-4.2.2.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-4.2.2.RELEASE....

    Spring JDBC与事务管理

    javaEE 实验三 Spring JDBC与事务管理, 一、实验目的 1、掌握Spring JDBC的配置; 2、掌握JdbcTemplae类中增删改查方法的使用; 3、了解Spring事务管理的3个核心接口; 4、了解Spring事务管理的两种方式; 5、掌握...

    spring-jdbc-5.0.5.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.0.5.RELEASE.jar; 赠送原API文档:spring-jdbc-5.0.5.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.0.5.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.0.5.RELEASE....

    spring-jdbc-5.2.15.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.2.15.RELEASE.jar; 赠送原API文档:spring-jdbc-5.2.15.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.2.15.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.2.15....

    spring-jdbc-4.3.12.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-4.3.12.RELEASE.jar; 赠送原API文档:spring-jdbc-4.3.12.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-4.3.12.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-4.3.12....

    spring-jdbc-5.0.8.RELEASE-API文档-中文版.zip

    赠送jar包:spring-jdbc-5.0.8.RELEASE.jar; 赠送原API文档:spring-jdbc-5.0.8.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.0.8.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-jdbc-5.0.8.RELEASE....

    spring-jdbc-5.0.10.RELEASE-API文档-中英对照版.zip

    赠送jar包:spring-jdbc-5.0.10.RELEASE.jar; 赠送原API文档:spring-jdbc-5.0.10.RELEASE-javadoc.jar; 赠送源代码:spring-jdbc-5.0.10.RELEASE-sources.jar; 包含翻译后的API文档:spring-jdbc-5.0.10....

Global site tag (gtag.js) - Google Analytics