mybatis从入门到精通(一) 入门
mybatis从入门到精通(一) 入门
一丶什么是mybatis
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
-- 资料来源于官方文档
二丶入门文档资料
(mybatis其实很简单, 有一定编程基础的可以直接查看官方文档, 进行学习, 笔者认为这是一种进步, 可以获得第一手资料)
三丶准备开发环境
1. 笔者使用idea开发工具新建maven项目(至于如何安装使用idea开发工具, 可以直接百度, 本文不做介绍), 然后在maven仓库中搜索mybatis对应的坐标, 笔者使用的版本如下
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency>
可以将上面maven坐标复制到pom.xml文件中, 笔者完整的pom.xml配置文件可以点此查看
2. 准备mysql数据库
可以直接mysql官网下载社区版,(至于如何安装使用, 可以直接百度, 本文不做介绍). 可以使用mysql workbench 或者navicat等数据库界面工具导入执行user.sql和email.sql两个数据脚本, 至此环境准备结束
四丶准备mybatis配置文件
在resources文件夹新建mybatis-config.xml配置文件和datasource.properties数据源属性文件
mybatsi-config.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> <!-- 配置外部属性 --> <properties resource="datasource.properties" /> <!-- 添加日志实现 --> <settings> <setting name="logImpl" value="LOG4J"/> <!-- 是否开启下划线和驼峰式的自动转换, http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Auto-mapping --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <environments default="development"> <environment id="development" > <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> </configuration>
datasource.properties, 注意, username, password改成自身数据库对应的账号密码
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false username=root password=root
为方便调试, 添加log4j日志配置, 需要与mybatis-config.xml中的配置一致, 同时需要在pom.xml文件中引入对应的jar包
log4j.properties
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n # mybatis 打印sql log4j.logger.com.ttx.example.mapper=DEBUG
五丶准备数据库表实体类和对应的mapper文件
1. 在src/main/java中新建实体类, User
public class User { private Integer userId; private String userName; private Integer age; private String country; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
2.新建mapper接口类文件UserMapper, 并写下查询方法, 参数为userId, 注意, 当参数为多个时, 需要使用@Param注解标明参数的名称
public interface UserMapper { User selectUser(@Param("userId") int userId); }
3. 新建mapper对应的查询语句映射文件UserMapper.xml ,
注意, 名称需要和上一步的类名一致
其中, resultMap为查询结果的映射配置, 用于指定数据表字段名和user实体类属性名的映射关系, id指明该字段为数据唯一标识
<select>元素对应查询语句, id对应上一步中的查询方法名, resultMap指定如何映射转换查询结果,
'select * from user where user_id = #{userId}' 为查询语句, #{userId} 为查询的参数, 和上一步中的@Param("userId")对应
<?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="com.ttx.example.mapper.UserMapper"> <resultMap id="UserMap" type="com.ttx.example.entity.User"> <id column="user_id" property="userId"/> <result column="user_name" property="userName"/> <result column="age" property="age"/> <result column="country" property="country"/> </resultMap> <sql id="baseColumn"> user_id, user_name, age, country </sql> <select id="selectUser" resultMap="UserMap"> select * from user where user_id = #{userId} </select> </mapper>
六丶在mybatis-config.xml中添加UserMapper.xml映射文件
注意, <mappers>元素在<environments>元素下方
<mappers> <mapper resource="com/ttx/example/mapper/UserMapper.xml"/> </mappers>
七丶使用junit测试框架测试本demo
需要在pom.xml文件中引入对应的jar包
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
在src/test中新建对应的测试类
public class MybatisTests { private SqlSession sqlSession; private UserMapper userMapper; @Before public void init() throws IOException { //读取mybatis-config.xml配置文件 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //根据配置文件创建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); this.sqlSession=sqlSessionFactory.openSession(); this.userMapper=sqlSession.getMapper(UserMapper.class); } @After public void destroy(){ this.sqlSession.close(); } @Test public void selectTest(){ // 查询 User user=userMapper.selectUser(1); sqlSession.commit(); System.out.println("name: "+user.getUserName()+", age: "+user.getAge()); Assert.assertEquals(new Integer(1), user.getUserId()); } }
最后运行selectTest()方法即可
运行结果为:
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 41489123. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@27912e3] DEBUG [main] - ==> Preparing: select * from user where user_id = ? DEBUG [main] - ==> Parameters: 1(Integer)'socket' DEBUG [main] - <== Total: 1 name: ttx, age: 11 DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@27912e3] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@27912e3] DEBUG [main] - Returned connection 41489123 to pool.
注意事项, service层的通用模板如下, 本文的测试用例并没有这样写
SqlSession sqlSession=null; try{ sqlSession=sqlSessionFactory.openSession(); //默认是开启事务, 不自动提交 UserMapper userMapper=sqlSession.getMapper(UserMapper.class); User user=userMapper.selectUser(1); sqlSession.commit(); //提交事务 }catch (Exception e){ e.printStackTrace(); if(sqlSession!=null){ sqlSession.rollback(); //出现异常, 回滚 } }finally { if(sqlSession!=null){ sqlSession.close(); // 需要关闭连接 } }
完整源码: 点此查看
学习资料: