程序代码
<!--本示例采用DBCP连接池,应预先把DBCP的jar包复制到工程的lib目录下。 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池-->
<property name="dataSource" ref="dataSource"/>
<!--configLocation属性指定mybatis的核心配置文件-->
<property name="configLocation" value="config/Configuration.xml"/>
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例-->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象-->
<property name="mapperInterface" value="com.yihaomen.mybatis.inter.IUserOperation" />
</bean>
程序代码
package com.yihaomen.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yihaomen.mybatis.inter.IUserOperation;
import com.yihaomen.mybatis.model.Article;
import com.yihaomen.mybatis.model.User;
public class MybatisSprintTest {
private static ApplicationContext ctx;
static
{
ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
}
public static void main(String[] args)
{
IUserOperation mapper = (IUserOperation)ctx.getBean("userMapper");
//测试id=1的用户查询,根据数据库中的情况,可以改成你自己的.
System.out.println("得到用户id=1的用户信息");
User user = mapper.selectUserByID(1);
System.out.println(user.getUserAddress());
//得到文章列表测试
System.out.println("得到用户id为1的所有文章列表");
List<Article> articles = mapper.getUserArticles(1);
for(Article article:articles){
System.out.println(article.getContent()+"--"+article.getTitle());
}
}
}