spring中的jdbcTemplate
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章