首页 > 代码库 > spring中的jdbcTemplate
spring中的jdbcTemplate
spring核心配置文件中的内容
<!-- 注入dataSource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/db_user"></property> <property name="username" value="root"></property> <property name="password" value="258764547"></property> </bean> <!-- 注入jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- 在jdbcTemplate中注入dataSource属性 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 注入 userDaoImpl--> <bean id="userDaoImpl" class="com.yudo.dao.impl.UserDaoImpl"> <!-- 在userDaoImpl中注入jdbcTemplate属性 --> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean>
增,删,改的代码、
public class UserDaoImpl { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void add() { User user = new User(); user.setUsername("关羽"); user.setPassword("456"); user.setAge(43); user.setAddress("荆州"); String sql = "insert into t_user (username,password,age,address) values (?,?,?,?)"; jdbcTemplate.update(sql, user.getUsername(), user.getPassword(),user.getAge(), user.getAddress()); } public void delete() { String username = "张飞"; String sql = "delete from t_user where username=?"; jdbcTemplate.update(sql, username); } public void update() { String sql = "update t_user set age=?, address=? where username=?"; jdbcTemplate.update(sql, "45", "蜀国", "关羽"); }
查询功能:
<1.返回单一对象
//返回单一对象 public void find1() { String sql = "select * from t_user where username=?"; User user = jdbcTemplate.queryForObject(sql, new MapRow(), "关羽"); System.out.println(user); }
new MapRow()的对象
class MapRow implements RowMapper<User> { @Override public User mapRow(ResultSet arg0, int arg1) throws SQLException { // TODO Auto-generated method stub String username = arg0.getString("username"); String password = arg0.getString("password"); Integer age = arg0.getInt("age"); String address = arg0.getString("address"); User user = new User(); user.setUsername(username); user.setPassword(password); user.setAge(age); user.setAddress(address); return user; } }
<2.返回List集合
//返回List集合 public void find2(){ String sql = "select * from t_user"; List<User> list = jdbcTemplate.query(sql, new MapRow()); for (User user : list) { System.out.println(user); } }
测试类:
@Test public void DemoTest() { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); UserDaoImpl userDaoImpl = (UserDaoImpl) ctx.getBean("userDaoImpl"); // userDaoImpl.add(); // userDaoImpl.delete(); // userDaoImpl.update(); // userDaoImpl.find1(); userDaoImpl.find2(); }
对增,删,改,的批量操作时,用到方法batchUpdate(sql, batchArgs);
batchArgs为Object类的数组
spring中的jdbcTemplate
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。