需要的jar包如下,直接引入项目的。 maven还不太会用
applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="net.trustie.db"/>
</beans>
applicationContext-myBatis.xml:
</pre><pre code_snippet_id="592772" snippet_file_name="blog_20150129_6_8493227" name="code" class="html"></pre><pre code_snippet_id="592772" snippet_file_name="blog_20150129_5_1789028" name="code" class="html"><pre name="code" class="html"><?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-3.0.xsd">
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="net.trustie.db" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/db?characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="pwd" />
</bean>
</beans>
新建一个Interface:
public interface FlowDao {
@Insert("INSERT INTO ${targetTable} (${targetFields}) Select ${sourceFields} from ${sourceTable} where id > ${idBegin} and id < ${idEnd}")
public int moveData(@Param("sourceTable") String sourceTableName,@Param("targetTable") String targetTableName,
@Param("sourceFields") String sourceFields,@Param("targetFields") String targetFields,
@Param("idBegin")int idBegin,@Param("idEnd")int idEnd);
}
这个主要用于表的数据迁移的。
如何使用这个Dao呢?看下面的代码示例:
@Component
public class FlowDaoTest {
@Resource
private FlowDao flowDao;
public void test()
{
flowDao.moveData("posts","posts0","id,body","id,body",1,50);
}
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:/spring/applicationContext*.xml");
final FlowDaoTest flowDaoTest= applicationContext
.getBean(FlowDaoTest.class);
flowDaoTest.test();
}
}
这个是可以正常运行的,结果是posts0表中id<50的数据被复制到post表中
在这个过程中,Spring和Mybatis框架会帮我们做好多工作,包括实例化接口,自动注入等。
目前我对框架理解程度还不够,水平仅限于简单应用。