您的位置:首页 > 其它

第一个mybatis例子

2015-06-15 22:04 381 查看
步骤

1. 创建java工程

2. 导入jar包



3. 创建日志文件log4j.properties



4. 创建全局配置文件SqlMapConfig.xml

<?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>
<!-- spring整合后enviroments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理,事务由mybatis控制 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/user?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>


5.pojo类



6. 编写对应的java对象映射文件

<?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">
<!-- namespace命名空间 -->
<mapper namespace="user">
<!-- 根据用户id查询用户信息
id:唯一标识符,标识映射文件中的sql
parameterType:指定输入参数的类型
resultType:指定sql输出的java对象
#{}表示一个占位符,相当于sql中的?占位符
#{id}表示接收输入的参数
-->
<select id="findUserById" parameterType="int" resultType="cn.wwmtek.mybatis.po.User">
select * from user where id = #{id}
</select>
</mapper>


7.将java对象映射文件加入SqlMapConfig.xml中



8.编写测试代码

@Test
public void findUserById() {
String resource = "SqlMapConfig.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("user.findUserById", 1);
System.out.println(user.toString());
sqlSession.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: