赞
踩
配置类:
@ComponentScan("com.Zjy.jdbcTemplate") @Configuration public class jdbcConfig { //数据源 @Bean public DataSource dataSource()throws Exception{ ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("root"); dataSource.setPassword("root"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql:///test2"); return dataSource; } @Bean public JdbcTemplate jdbcTemplate()throws Exception{ //在容器中找组件,特殊处理,不会重写创建 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource()); return jdbcTemplate; } }
javabean
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private Integer id;
private String username;
private Integer age;
}
dao:
@Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void test1(){ String sql = "select count(*) from tbl_user "; Integer integer = jdbcTemplate.queryForObject(sql, Integer.class); System.out.println(integer); } public User test2(Integer id) { String sql = "select * from tbl_user where id = ?"; User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id); return user; } public List<User> test3(){ String sql = "select * from tbl_user"; List<User> list = jdbcTemplate.query (sql, new BeanPropertyRowMapper<User>(User.class)); return list; } public void test4(List<Object[]> batchArgs){ String sql = "insert into tbl_user values(null, ?, ?)"; List<Object> list = new ArrayList<>(); list.add(new Object[]{"A", 33}); list.add(new Object[]{"C", 32}); jdbcTemplate.batchUpdate(sql, batchArgs); } }
service:
@Service public class UserService { @Autowired UserDao userDao; public void test1(){ userDao.test1(); } public User test2(Integer id){ User user = userDao.test2(id); return user; } public List<User> test3(){ List<User> list = userDao.test3(); return list; } public void test4(List<Object[]> batchArgs){ List<Object> list = new ArrayList<>(); list.add(new Object[]{"A", 33}); list.add(new Object[]{"C", 32}); userDao.test4(batchArgs); } }
test
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = jdbcConfig.class) public class test { @Autowired UserService userService; @Test public void test1(){ userService.test1(); } @Test public void test2(){ User user = userService.test2(1); System.out.println(user); } @Test public void test3(){ List<User> list = userService.test3(); list.forEach(user -> System.out.println(user)); } @Test public void test4(){ List<Object[]> list = new ArrayList<>(); list.add(new Object[]{"A", 33}); list.add(new Object[]{"C", 32}); userService.test4(list); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。