package com.mycompany.shequ.bean; public class Forum { private int fid; private String name; public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.mycompany.shequ.dao; import com.mycompany.shequ.bean.Forum; public interface ForumDao { public void insert(Forum forum); }
package com.mycompany.shequ.dao.impl; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport; import com.mycompany.shequ.bean.Forum; import com.mycompany.shequ.dao.ForumDao; public class ForumDaoImpl extends JdbcDaoSupport implements ForumDao { private DataSource dataSource; @Override public void insert(Forum forum) { String sql = "INSERT INTO hnsq_forum(name) values(?)"; getJdbcTemplate().update(sql, new Object[]{forum.getName()}); } }
<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-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/b_shequ_two" /> <property name="username" value="root" /> <property name="password" value="" /> </bean> </beans>
<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-2.5.xsd"> <import resource="spring-datasource.xml" /> <bean id="forumDao" class="com.mycompany.shequ.dao.impl.ForumDaoImpl"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
16.测试类ForumDaoImplTest的内容如下
package com.mycompany.shequ.dao.impl; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mycompany.shequ.bean.Forum; import com.mycompany.shequ.dao.ForumDao; public class ForumDaoImplTest { @Test public void testInsert(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ForumDao forumDao = (ForumDao) context.getBean("forumDao"); Forum forum = new Forum(); forum.setName("demo4"); forumDao.insert(forum); } }
17.运行测试方法testInsert,执行结果如图所示
18.查看数据库中的结果,如图所示
本文出自 “素颜” 博客,请务必保留此出处http://suyanzhu.blog.51cto.com/8050189/1909083
原文地址:http://suyanzhu.blog.51cto.com/8050189/1909083