赞
踩
service层:业务层(业务逻辑)
dao层:持久层(直接操作数据库)
创建service对象
package jdbctemplateioc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("userService2")
public class UserService2 {
@Autowired
private UserDao2 userDao2;
public void add(){
userDao2.add();
}
}
创建dao对象
package jdbctemplateioc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component("userDao2") public class UserDao2 { @Autowired private JdbcTemplate jdbcTemplate; public void add(){ String sql="insert into user values(?,?)"; int rows=jdbcTemplate.update(sql, "王小明","147258"); if(rows>0)System.out.println("成功"); else System.out.println("失败"); } }
创建jdbctemplateioc2.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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <!-- 连接池配置 --><!--需要导入c3p0jar包 --> <context:component-scan base-package="jdbctemplateioc"></context:component-scan><!--开启注解 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3307/spring?useUnicoding=true&characterEncoding=utf8&useSSL=false"></property> <property name="user" value="root"></property> <property name="password" value="513721abcd"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
测试代码:
package jdbctemplateioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("jdbctemplateioc2.xml");
UserService2 userService2= (UserService2) context.getBean("userService2");
userService2.add();
}
}
注意:配置文件中的dataSource和JdbcTemplate都是导入的包中自带的
JdbcTemplate需要注入dataSource属性
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。