04_Spring结合数据库JDBC

张创琦

代码详见 Spring04_jdbc

实体类

  1. package com.kkb.pojo;
  2. public class Team {
  3. private Integer id;
  4. private String name;
  5. private String location;
  6. public Team() {
  7. }
  8. public Team(String name, String location) {
  9. this.name = name;
  10. this.location = location;
  11. }
  12. public Integer getId() {
  13. return id;
  14. }
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public String getLocation() {
  25. return location;
  26. }
  27. public void setLocation(String location) {
  28. this.location = location;
  29. }
  30. @Override
  31. public String toString() {
  32. return "Team{" +
  33. "id=" + id +
  34. ", name='" + name + '\'' +
  35. ", location='" + location + '\'' +
  36. '}';
  37. }
  38. }

TeamDao.java

  1. package com.kkb.dao;
  2. import com.kkb.pojo.Team;
  3. import org.springframework.jdbc.core.RowMapper;
  4. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.List;
  8. import java.util.Map;
  9. public class TeamDao extends JdbcDaoSupport {
  10. /**
  11. * 处理我们的结果,自己封装结果的方法
  12. * @param resultSet
  13. * @return
  14. * @throws SQLException
  15. */
  16. public Team handleResult(ResultSet resultSet) throws SQLException {
  17. Team team = new Team();
  18. team.setId(resultSet.getInt("tid"));
  19. team.setName(resultSet.getString("tname"));
  20. team.setLocation(resultSet.getString("location"));
  21. return team;
  22. }
  23. //插入
  24. public int insert(Team team) {
  25. String sql = " insert into team (tname, location) values (?, ?) ";
  26. return this.getJdbcTemplate().update(sql, team.getName(), team.getLocation());
  27. //return this.getJdbcTemplate().update(sql, "湖人", "洛杉矶");
  28. //update适用于增删改
  29. }
  30. //更新
  31. public int update(Team team){
  32. String sql = " update team set tname = ? , location = ? where tid = ? ";
  33. return this.getJdbcTemplate().update(sql, team.getName(), team.getLocation(), team.getId());
  34. }
  35. //删除
  36. public int del(int id) {
  37. String sql = " delete from team where tid = ? ";
  38. return this.getJdbcTemplate().update(sql, id);
  39. }
  40. //查询,查询比上面其他三个特殊
  41. public Team findById(int id){
  42. String sql = " select * from team where tid=? ";
  43. return this.getJdbcTemplate().queryForObject(sql, new Object[]{id}, new RowMapper<Team>(){
  44. @Override
  45. public Team mapRow(ResultSet resultSet, int i) throws SQLException {
  46. return handleResult(resultSet);
  47. }
  48. });
  49. }
  50. public List<Team> findAll(){
  51. String sql = " select * from team ";
  52. return this.getJdbcTemplate().query(sql, new RowMapper<Team>() {
  53. @Override
  54. public Team mapRow(ResultSet resultSet, int i) throws SQLException {
  55. return handleResult(resultSet);
  56. }
  57. });
  58. }
  59. // getCount 查询受影响的行数
  60. public int getCount(){
  61. String sql = " select count(tid) from team ";
  62. return this.getJdbcTemplate().queryForObject(sql, Integer.class);
  63. }
  64. //求tid的最大值和最小值
  65. public Map<String, Object> getMany(){
  66. String sql = " select max(tid), min(tid) from team ";
  67. return this.getJdbcTemplate().queryForMap(sql);
  68. }
  69. }

测试

  1. package com.kkb.test;
  2. import com.kkb.dao.TeamDao;
  3. import com.kkb.pojo.Team;
  4. import com.mchange.v2.c3p0.ComboPooledDataSource;
  5. import org.junit.Test;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;
  8. import org.springframework.jdbc.core.JdbcTemplate;
  9. import java.beans.PropertyVetoException;
  10. import java.util.List;
  11. import java.util.Map;
  12. import java.util.Set;
  13. public class Test01 {
  14. ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
  15. @Test
  16. public void test01() throws PropertyVetoException {
  17. //创建数据源
  18. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  19. dataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); //记得抛出异常
  20. dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springJDBC? serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false");
  21. dataSource.setUser("root");
  22. dataSource.setPassword("123456");
  23. //使用JDBCTemplate
  24. JdbcTemplate template = new JdbcTemplate(dataSource);
  25. String sql = " insert into team (tname, location) values (?, ?) ";
  26. int update = template.update(sql, "勇士", "金州");
  27. System.out.println("插入的结果"+ update);
  28. }
  29. //基于xml配置实现, insert
  30. @Test
  31. public void test02(){
  32. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  33. Team team = new Team();
  34. team.setName("湖人");
  35. team.setLocation("洛杉矶");
  36. int res = dao.insert(team);
  37. System.out.println("插入数据的结果: "+res);
  38. }
  39. //基于xml配置实现, update
  40. @Test
  41. public void test03(){
  42. ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
  43. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  44. Team team = new Team();
  45. team.setName("小牛");
  46. team.setLocation("达拉斯");
  47. team.setId(4);
  48. int res = dao.update(team);
  49. System.out.println("更新数据的结果: "+res);
  50. }
  51. //基于xml配置实现, delete
  52. @Test
  53. public void test04(){
  54. ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
  55. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  56. int res = dao.del(4);
  57. System.out.println("删除数据的结果: "+res);
  58. }
  59. //findById 测试查询
  60. @Test
  61. public void test05(){
  62. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  63. Team team = dao.findById(1);
  64. System.out.println(team);
  65. }
  66. //findAll 测试查询
  67. @Test
  68. public void test06(){
  69. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  70. List<Team> team = dao.findAll();
  71. for(Team t: team){
  72. System.out.println(t);
  73. }
  74. }
  75. //getCount
  76. @Test
  77. public void test07(){
  78. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  79. int count = dao.getCount();
  80. System.out.println("受影响的总行数:"+count);
  81. }
  82. //getMany 获取最大值和最小值
  83. @Test
  84. public void test08(){
  85. TeamDao dao = (TeamDao) ac.getBean("teamDao");
  86. int count = dao.getCount();
  87. System.out.println("查询的总行数:"+count);
  88. Map<String, Object> many = dao.getMany();
  89. Set<Map.Entry<String, Object>> entries = many.entrySet();
  90. for(Map.Entry<String, Object> entry: entries){
  91. System.out.println(entry.getKey()+"--------"+entry.getValue());
  92. }
  93. }
  94. }

application.xml

注意:& 要写成 & a m p ;

  1. <!-- 创建JdbcTemplate的数据源 -->
  2. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  3. <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
  4. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springJDBC?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false"></property>
  5. <property name="user" value="root"></property>
  6. <property name="password" value="123456"></property>
  7. </bean>
  8. <!-- 创建JdbcTemplate -->
  9. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  10. <property name="dataSource" ref="dataSource"></property>
  11. </bean>
  12. <bean id="teamDao" class="com.kkb.dao.TeamDao">
  13. <property name="jdbcTemplate" ref="jdbcTemplate"></property>
  14. </bean>

05_事务管理

张创琦

代码详见 Spring04_jdbc

方法1: 加入@Transactional

  1. package com.kkb.service;
  2. import com.kkb.dao.TeamDao;
  3. import com.kkb.pojo.Team;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.transaction.annotation.Propagation;
  7. import org.springframework.transaction.annotation.Transactional;
  8. @Service
  9. public class TeamService {
  10. @Autowired
  11. private TeamDao teamDao;
  12. //事务
  13. //如果注解掉事务的话,需要注释掉以下注解内容,然后通过xml方式配置
  14. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
  15. public int insert(Team team){
  16. //事务存在时,一条成功另一条失败则会发生回滚
  17. int num = teamDao.insert(team);
  18. System.out.println("第一条执行结果 num1: "+ num);
  19. //System.out.println(10/0);
  20. int num2 = teamDao.insert(team);
  21. System.out.println("第一条执行结果 num2: "+ num2);
  22. return num + num2; //只有1和2都成功才会返回结果
  23. }
  24. }

方法2: xml注释

xml的优点: 可以统一管理,不用对每一个方法加入注解配置。

第一步:需要将上面一部分代码里的 @Transactional 注释掉

application.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <!-- context扫描 -->
  10. <context:component-scan base-package="com.kkb"/>
  11. <!-- 创建JdbcTemplate的数据源 -->
  12. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  13. <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
  14. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springJDBC?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false"></property>
  15. <property name="user" value="root"></property>
  16. <property name="password" value="123456"></property>
  17. </bean>
  18. <!-- 创建JdbcTemplate -->
  19. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  20. <property name="dataSource" ref="dataSource"></property>
  21. </bean>
  22. <bean id="teamDao" class="com.kkb.dao.TeamDao">
  23. <property name="jdbcTemplate" ref="jdbcTemplate"></property>
  24. </bean>
  25. <!-- 启动事务的注解,最上方引入content -->
  26. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  27. <property name="dataSource" ref="dataSource"></property>
  28. </bean>
  29. <!-- 跟注解相关 -->
  30. <tx:annotation-driven transaction-manager="transactionManager"/>
  31. <!-- 基于配置文件配置事务注解的话,transactionManager必须存在,tx:annotation-driven不需要存在 -->
  32. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  33. <tx:attributes>
  34. <!-- 默认进行回滚 rollback-for="" -->
  35. <tx:method name="insert*" propagation="REQUIRED" />
  36. <tx:method name="add*" propagation="REQUIRED" />
  37. <!-- find默认只读 read-only="true" -->
  38. <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
  39. </tx:attributes>
  40. </tx:advice>
  41. <aop:config>
  42. <aop:pointcut id="pt" expression="execution(* com.kkb.service..*.*(..))"/>
  43. <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
  44. </aop:config>
  45. </beans>

pom.xml配置相关依赖

  1. <!-- 事务的依赖 -->
  2. <dependency>
  3. <groupId>org.aspectj</groupId>
  4. <artifactId>aspectjweaver</artifactId>
  5. <version>1.9.6</version>
  6. </dependency>