關於Spring-JDBC測試類的簡單封裝
阿新 • • 發佈:2022-04-02
關於Spring-JDBC測試類的簡單封裝
1、簡單封裝
/** * Created with IntelliJ IDEA. * * @Author: Suhai * @Date: 2022/04/02/18:23 * @Description: */ public class JdbcTest02 { private JdbcTemplate jdbcTemplate; //方法執行前先執行Before註解下的方法 @Before public void init() { // 得到Spring上下文環境 ApplicationContext ac = new ClassPathXmlApplicationContext("springjdbc.xml"); // 得到模板類 JdbcTemplate物件 jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate"); } @Test public void testQueryCount() { // 定義sql語句 String sql = "select count(1) from student"; // 執行查詢操作(無引數) Integer total= jdbcTemplate.queryForObject(sql, Integer.class); System.out.println("總記錄數:" + total); } @Test public void testQueryCountByUserId() { // 定義sql語句 String sql = " select count(1) from student where id = ?"; // 執行查詢操作(有引數) Integer total = jdbcTemplate.queryForObject(sql, Integer.class, 1); System.out.println("總記錄數:" + total); } }
2、註解封裝
/** * Created with IntelliJ IDEA. * * @Author: Suhai * @Date: 2022/04/02/18:23 * @Description: */ @RunWith(SpringJUnit4ClassRunner.class) // 將junit測試加到spring環境中 @ContextConfiguration(locations = {"classpath:springjdbc.xml"}) // 設定要載入的資原始檔 public class JdbcTest03 { @Resource private JdbcTemplate jdbcTemplate; @Test public void testQueryCount() { // 定義sql語句 String sql = "select count(1) from student"; // 執行查詢操作(無引數) Integer total= jdbcTemplate.queryForObject(sql, Integer.class); System.out.println("總記錄數:" + total); } @Test public void testQueryCountByUserId() { // 定義sql語句 String sql = " select count(1) from student where id = ?"; // 執行查詢操作(有引數) Integer total = jdbcTemplate.queryForObject(sql, Integer.class, 1); System.out.println("總記錄數:" + total); } }
3、繼承父類通用封裝
/**
* 通用的測試環境,需要使用環境的直接繼承類即可
*/
@RunWith(SpringJUnit4ClassRunner.class) // 將junit測試加到spring環境中
@ContextConfiguration(locations = {"classpath:springjdbc.xml"}) // 設定要載入的資原始檔
public class BaseTest {
}
public class JdbcTest04 extends BaseTest { @Resource private JdbcTemplate jdbcTemplate; @Test public void testQueryCount() { // 定義sql語句 String sql = "select count(1) from student"; // 執行查詢操作(無引數) Integer total = jdbcTemplate.queryForObject(sql, Integer.class); System.out.println("總記錄數:" + total); } }