第一个mybatis例子
2015-06-15 22:04
381 查看
步骤
1. 创建java工程
2. 导入jar包
3. 创建日志文件log4j.properties
4. 创建全局配置文件SqlMapConfig.xml
5.pojo类
6. 编写对应的java对象映射文件
7.将java对象映射文件加入SqlMapConfig.xml中
8.编写测试代码
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(); } } } }
相关文章推荐
- [编程题]Be Unique (赌徒下注问题)
- C++ Tree类
- [HDOJ2065]"红色病毒"问题
- HMMStateState API
- Codeforces 551E - GukiZ and GukiZiana(分块)
- MYSQL查询优化:profile功能
- [编程题]Shuffling Machine (洗牌程序)
- android"百码"2——基础小知识积累(逐步完善)2015-06-15
- php实现上传图片保存到数据库的方法
- sgu220&sgu221
- sgu220&sgu221 分类: sgu 2015-06-15 22:01 24人阅读 评论(0) 收藏
- python的Nginx切割脚本
- 37Exchange 2010升级到Exchange 2013-测试邮件流(未切换公网发布)
- ADF常见的代码陷阱(一)
- Cracking the Code Interview 4.3 Array to Binary Tree
- TCP深入解析(二)
- hdu 1316 How Many Fibs?
- 15周《C++语言基础》程序阅读——二进制文件及文件的随机读写(2)(3)
- Word Break
- 汇编语言基础4