mybatis的配置:
1.下载mybatis.3.4.4.jar,加入此jar包引用。同时将它复制到发布目录下的WEB-INF\lib,以防运行时找不到类库。
2.建立配置文件mybatis-config.xml,文件内容从官网的示例复制下来,修改下(我的是连sqlserver的)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=xxxxxxx;"/>
<property name="username" value="xxxxxxxxx"/>
<property name="password" value="xxxxxx"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="jl/bank/controller/UserMapper.xml"/>
</mappers>
</configuration>
生成文件后遇到的首要问题是这个文件要放在哪里,在程序中如何调用?
按官方文档说法,可以根据类路径,文件路径来存放、查找。
我把它放在web项目的的src/jl/bank/contrller目录下(这并非是官方推荐的目录)
mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="JL.BO.MyBatis">
<select id="selectUser" resultType="map">
select * from sys_user where sys_user_id > #{id}
</select>
</mapper>
为了能返回多条记录,select语句选择user_id>=#{id}。另外在xml中“>”要写成">"
mapper文件放在与mybatis-config.xml相同的目录。
然后是在java代码中调用,为简单起见,我就让它返回List<HashMap>。调用点就放在Controller中,输出结果在View中显示出来:
@RequestMapping(value="/bank/mybatis", produces="text/html;charset=UTF-8")
public ModelAndView testMybatis(){
ModelAndView modelAndView = new ModelAndView("/bank/batis");
modelAndView.addObject("title", "Mybatis");
String resource = "jl/bank/controller/mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
List<HashMap<String,Object>> users=session.selectList("JL.BO.MyBatis.selectUser", 15);
String result="";
for(HashMap<String,Object> user:users)
{
result+=user.get("LOGIN_NAME")+",";
}
modelAndView.addObject("result",result);
session.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return modelAndView;
}
输出结果:
本文介绍MyBatis的基本配置步骤,包括引入依赖、创建配置文件,并演示如何通过Java代码调用MyBatis进行数据库操作。
5914

被折叠的 条评论
为什么被折叠?



