标签:
在使用Mybatis从数据库中获取记录时,仅编写一个映射xml文件即可。这便是mybatis的强大之处,据说可以比普通jdbc要节省95%的代码。
先来看看如何获取记录,工程配置请参考《一、MyBatis系列:第一个MyBatis工程》:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 <mapper namespace="test"> 5 <select id="getUserById" parameterType="int" resultType="map"> 6 SELECT * FROM user where id = #{value} 7 </select> 8 <select id="getUsers" resultType="map"> 9 SELECT * FROM user 10 </select> 11 </mapper>
理解一下节点元素:
注意 parameterType 是不接受多个参数的,如果存在多个参数,需要封装为一个 POJO 类型。
1 @Test 2 public void getUsersTest() throws IOException { 3 InputStream stream = Resources.getResourceAsStream("MybatisConfig.xml"); 4 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream); 5 SqlSession sqlSession = factory.openSession(); 6 try { 7 // 读取一条记录,返回 Map 结果类型. 8 Map<Object, Object> user = sqlSession.selectOne("test.getUserById", 1); 9 System.out.println(user); 10 11 // 读取多条记录,返回 List<Map> 结果类型. 12 List<Map<Object, Object>> users = sqlSession.selectList("test.getUsers"); 13 System.out.println(users); 14 } finally { 15 sqlSession.close(); 16 } 17 }
查看日志输出:
DEBUG [main] - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 603650290.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@23faf8f2]
DEBUG [main] - ==> Preparing: SELECT * FROM user where id = ?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
{birthday=2014-07-10, address=北京市, sex=2, id=1, username=王五, attrs={"参数1":"参数值1"}}
DEBUG [main] - ==> Preparing: SELECT * FROM user
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 6
[{birthday=2014-07-10, address=北京市, sex=2, id=1, username=王五, attrs={"参数1":"参数值1"}}, {birthday=2014-07-10, address=北京市, sex=1, id=10, username=张三, attrs={"参数1":"参数值1"}}, ..... }]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@23faf8f2]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@23faf8f2]
DEBUG [main] - Returned connection 603650290 to pool.
三、MyBatis系列:Mapper 映射 之 通过mapper映射文件来读取数据库记录
标签:
原文地址:http://www.cnblogs.com/xialiang/p/4604403.html