赞
踩
使用JDBCTemplate
首先创建一个Dao接口和实现类,添加注解创建对象,然后创建一个数据库表和实体类
创建service层代码,并注入Dao接口的bean对象,调用接口方法
配置文件中【有错】
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- 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/context http://www.springframework.org/schema/context/spring-context.xsd">
-
- <context:component-scan base-package="xlw.com.jdbcTemplate"></context:component-scan>
-
- <context:property-override location="classpath:jdbc.properties"></context:property-override>
-
- <bean id="jdbc" class="com.alibaba.druid.pool.DruidDataSource">
- <property name="driverClassName" value="${druid.DriverClassname}"></property>
- <property name="url" value="${druid.url}"></property>
- <property name="username" value="${druid.username}"></property>
- <property name="password" value="${druid.password}"></property>
- </bean>
-
- <!--创建JDBCTemplate bean对象-->
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="jdbc"></property>
- </bean>
- </beans>
Dao中
- @Component
- public interface UserDao {
- void add(User user);
- }
DaoImpl中
- @Repository
- public class UserDaoImpl implements UserDao {
- @Autowired
- private JdbcTemplate jdbcTemplate;
-
- @Override
- public void add(User user) {
- String sql = "insert into o_User values (?,?,?)";
- int update = jdbcTemplate.update(sql, null, user.getUsername(), user.getPassword());
- System.out.println(update);
- }
- }
Service中【没建立接口】
- @Service
- public class UserService {
- @Autowired
- private UserDao userDao;
-
- public void addUser(User user){
- userDao.add(user);
- }
- }
随便建一个测试类
- ApplicationContext context = new ClassPathXmlApplicationContext("hao.xml");
- @Test
- public void testJDBCTemplate(){
- UserService userService = context.getBean("userService", UserService.class);
- User user = new User();
- user.setUsername("老王");
- user.setPassword("123abc");
- System.out.println(user.getPassword());
- userService.addUser(user);
- }
问题出现了,本来会输出一个影响行数。 但是报错了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。