时间:2021-07-01 10:21:17 帮助过:40人阅读
编写目标类:
import org.springframework.jdbc.core.JdbcTemplate; public class UserDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void insert(){ String sql="insert into user (name,deptid) values (?,?)"; jdbcTemplate.update(sql, new Object[]{"caoyc",3}); } }
配置xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"></property> <property name="password" value="123456"></property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property> </bean> <!--配置jdbcTemplate对象,并为类中的dataSource属性注入值 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置userDao对象,并为类中的属性注入值 --> <bean id="userDao" class="com.jdbcTemplate.UserDao"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> </beans>
编写测试代码:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("bean5.xml"); UserDao userDao= (UserDao) context.getBean("userDao"); userDao.insert(); } }
运行结果:数据正常入库。
Spring--JdbcTemplate
标签:object instance cut app png host group led 目标