MyBatis是一个优秀的持久层框架。原生的jdbc操作存在大量的重复性代码(如注册驱动,创建连接,创建statement,结果集检测等)。框架的作用就是把这些繁琐的代码封装。

MyBatis通过XML或者注解的方式将要执行的sql语句配置起来,并通过java对象和sql语句映射成最终执行的sql语句。最终由MyBatis框架执行sql,并将结果映射成java对象并返回。

Mybatis项目实例可以根据Mybatis官网搭建:https://mybatis.org/mybatis-3/

开始搭建:

1、引入jar包依赖

     <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> <!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>

2、引入mybatis的全局配置文件,该文件配置了mybatis的运行环境等信息

<?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>
<!-- 引入外部的java配置文件(properties文件) -->
<!-- property子标签执行顺序会早于 resource属性的解析 -->
<properties resource="db.properties">
<!-- <property name="db.username" value="123"/> -->
<property name="username" value="123" />
</properties> <!-- 自定义别名 -->
<typeAliases>
<!-- 批量别名设置,指定需要别名设置的po类的包名。默认别名就是类名(大小写都可以) -->
<package name="com.zick.mybatis.po" />
<!-- 单个别名设置 -->
<!-- <typeAlias type="com.kkb.mybatis.po.User" alias="user"/> -->
</typeAliases>
<!-- 数据源连接,实际项目中会交给spring进行管理 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<!-- <property name="username" value="${username}" /> -->
<property name="password" value="${db.password}" />
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml" />
</mappers>
</configuration>

3、准备User sqlMapper文件、User实体对象

	<select id="findUserById" parameterType="java.lang.Integer" resultType="User" >
SELECT * FROM user WHERE id = #{id}
</select> <!-- 添加用户 -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.zick.mybatis.po.User">
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert> public class User implements Serializable { private int id;
private String username;
private Date birthday;
private String sex;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() { return birthday; }
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} @Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
+ address + "]";
}
}

4、编写测试用例

public class UserMapperTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
public void init() throws Exception {
// 指定全局配置文件路径
String resource = "SqlMapConfig.xml";
// 加载资源文件(全局配置文件和映射文件)
InputStream inputStream = Resources.getResourceAsStream(resource);
// 还有构建者模式,去创建SqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testFindUserById() throws Exception {
// 构造UserMapper对象(sqlSession)
SqlSession sqlSession = sqlSessionFactory.openSession();
// 需要传的参数就是被代理的Mapper接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 调用UserMapper对象的findUserById
User user = userMapper.findUserById(1);
System.out.println(user);
} @Test
public void testInsert() throws Exception {
// 构造UserMapper对象(sqlSession)
SqlSession sqlSession = sqlSessionFactory.openSession();
// 需要传的参数就是被代理的Mapper接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = new User();
user.setUsername("隔壁老詹12");
user.setAddress("洛杉矶湖人");
// 执行增删改操作,清空缓存
userMapper.insertUser(user);
System.out.println(user);
// sqlSession.commit();
}

特别的,Mybatis默认执行完insert语句并不会自动提交,需要手动或者设置自动提交。

建表语句如下:

CREATE TABLE `NewTable` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名称' ,
`birthday` date NULL DEFAULT NULL COMMENT '生日' ,
`sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别' ,
`address` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址' ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci

本身搭建Mybatis项目Demo难度并不大,但接下来,更多的是以此为基点,开始对Mybatis的源码进行跟踪学习,并记录其中的点滴。

最新文章

  1. linux定时任务crond export变量问题
  2. sass的四种css编译风格
  3. wcf第1步
  4. JSP内置对象--request对象
  5. Android中的Intent Filter匹配规则介绍
  6. iOS exit(0); 直接退出程序
  7. 基于duilib实现的可滑动tab标签控件
  8. qq第3方登录的JS实现方式记录
  9. Android - Service启动机制
  10. Sass的控制命令(循环)
  11. Windows8 Metro快捷键 | Win8迷
  12. HDU 2825 AC自动机+DP
  13. Linux系统手动安装rpm包依赖关系分析(以Kernel升级为例)
  14. GDB: basics
  15. be 动词
  16. mysql主从复制笔记
  17. 【数据结构】B-Tree, B+Tree, B*树介绍
  18. 学习经验分享(最近听了一节Java公开课)
  19. c++使用cmake创建dpdk项目
  20. 【转载】SVN使用教程总结

热门文章

  1. mysql主从模式部署
  2. Prometheus之Exporter开发
  3. Spring boot +Thymeleaf 搭建springweb
  4. Git【常见知识点速查】
  5. js计算两个时间相差
  6. djano jwt 的使用
  7. What number should I guess next ?——由《鹰蛋》一题引发的思考
  8. 实验一 C运行环境与最简单的程序设计
  9. 01 How does C Programming work ? C语言如何工作?
  10. Matlab中加汉明窗 ahmming 作用