# spring 整合 jdbc template(xml配置方式) ## 一、说明 #### 1.1 项目结构
#### 1.2 项目依赖 ```xml org.springframework spring-jdbc ${spring-base-version} mysql mysql-connector-java 8.0.13 com.oracle ojdbc6 11.2.0.3.0 ``` ## 二、 spring 整合 jdbc template #### 1、在resources文件夹下新建数据库配置文件jdbc.properties ```properties # mysql 数据库配置 mysql.driverClassName=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://localhost:3306/mysql mysql.username=root mysql.password=root # oracle 数据库配置 oracle.driverClassName=oracle.jdbc.driver.OracleDriver oracle.url=jdbc:oracle:thin:@//IP地址:端口号/数据库实例名 oracle.username=用户名 oracle.password=密码 ``` #### 2、配置Jdbc数据源并定义事务管理器 ```xml ``` #### 3、新建查询接口及其实现类,这里我查询的表是mysql和oracle中的字典表 ```java @Repository public class MysqlDaoImpl implements MysqlDao { @Autowired private JdbcTemplate jdbcTemplate; /** * 更多JDBC 的使用可以参考官方文档 * @see JdbcTemplate */ public List get() { List relations = jdbcTemplate.query("select * from help_keyword where help_keyword_id = ? ", new Object[]{691}, new RowMapper() { public Relation mapRow(ResultSet rs, int rowNum) throws SQLException { Relation relation = new Relation(); relation.setId(rs.getString("help_keyword_id")); relation.setName(rs.getString("name")); return relation; } }); return relations; } } ``` ```java @Repository public class OracleDaoImpl implements OracleDao { @Autowired private JdbcTemplate jdbcTemplate; /** * 更多JDBC 的使用可以参考官方文档 * @see JdbcTemplate */ public List get() { List flows = jdbcTemplate.query("select * from APEX_030200.WWV_FLOW_CALS where ID = ? ", new Object[]{217584603977429772L}, new RowMapper() { public Flow mapRow(ResultSet rs, int rowNum) throws SQLException { Flow flow = new Flow(); flow.setId(rs.getLong("ID")); flow.setFlowId(rs.getLong("FLOW_ID")); flow.setPlugId(rs.getLong("PLUG_ID")); return flow; } }); return flows; } } ``` #### 4.新建测试类进行测试 ```java @RunWith(SpringRunner.class) @ContextConfiguration({"classpath:springApplication.xml"}) public class MysqlDaoTest { @Autowired private MysqlDao mysqlDao; @Test public void get() { List relations = mysqlDao.get(); if (relations != null) { for (Relation relation : relations) { System.out.println(relation.getId() + " " + relation.getName()); } } } } ``` ```java @RunWith(SpringRunner.class) @ContextConfiguration({"classpath:springApplication.xml"}) public class OracleDaoTest { /*注入接口时: 如果接口有多个实现类 可以用这个注解指定具体的实现类*/ @Qualifier("oracleDaoImpl") @Autowired private OracleDao oracleDao; @Test public void get() { List flows = oracleDao.get(); if (flows != null) { for (Flow flow : flows) { System.out.println(flow.getId() + " " + flow.getPlugId()); } } } } ```