MyBatis快速入门
1. 添加MyBatis的坐标----在pom.xml中导入jar文件
2. 创建user数据表
3. 编写User实体类和用户持久层
4. 在resources下创建database.properties 数据库连接配置文件
5. 编写映射文件UserMapper.xml
6. 编写核心文件mybatis.xml
7. 编写测试类
MyBatis快速入门
1. 添加MyBatis的坐标----在pom.xml中导入jar文件
1 <dependencies>
2 <dependency>
3 <groupId>junit</groupId>
4 <artifactId>junit</artifactId>
5 <version>4.11</version>
6 <scope>test</scope>
7 </dependency>
8 <dependency>
9 <groupId>org.mybatis</groupId>
10 <artifactId>mybatis</artifactId>
11 <version>3.5.5</version>
12 </dependency>
13 <dependency>
14 <groupId>log4j</groupId>
15 <artifactId>log4j</artifactId>
16 <version>1.2.17</version>
17 </dependency>
18 <dependency>
19 <groupId>org.projectlombok</groupId>
20 <artifactId>lombok</artifactId>
21 <version>1.16.10</version>
22 </dependency>
23 <dependency>
24 <groupId>mysql</groupId>
25 <artifactId>mysql-connector-java</artifactId>
26 <version>5.1.49</version>
27 </dependency>
28 <dependency>
29 <groupId>org.projectlombok</groupId>
30 <artifactId>lombok</artifactId>
31 <version>1.16.10</version>
32 </dependency>
33 </dependencies>
2. 创建user数据表
1 -- auto-generated definition
2 create table smbms_user
3 (
4 id bigint auto_increment comment '主键ID'
5 primary key,
6 userCode varchar(15) null comment '用户编码',
7 userName varchar(15) null comment '用户名称',
8 userPassword varchar(15) null comment '用户密码',
9 gender int(10) null comment '性别(1:女、 2:男)',
10 birthday date null comment '出生日期',
11 phone varchar(15) null comment '手机',
12 address varchar(30) null comment '地址',
13 userRole int(10) null comment '用户角色(取自角色表-角色id)',
14 createdBy bigint null comment '创建者(userId)',
15 creationDate datetime null comment '创建时间',
16 modifyBy bigint null comment '更新者(userId)',
17 modifyDate datetime null comment '更新时间'
18 )
19 collate = utf8_unicode_ci;
3. 编写User实体类和用户持久层
1 package com.cma.pojo;
2
3 import lombok.*;
4
5 @Setter //生成set
6 @Getter //生成get
7 @AllArgsConstructor //有参构造函数
8 @NoArgsConstructor //无参构造函数
9 @ToString //重写tostring 拼接所有参数 便于打印
10 public class User {
11 private Integer id; //id
12 private String userCode; //用户编码
13 private String userName; //用户名称
14 private String userPassword; //用户密码
15 private Integer gender; //性别
16 private String birthday; //出生日期
17 private String phone; //电话
18 private String address; //地址
19 private Integer userRole; //用户角色
20 private Integer createdBy; //创建者
21 private String creationDate; //创建时间
22 private Integer modifyBy; //更新者
23 private String modifyDate; //更新时间
24 }
1 package com.cma.dao;
2
3 import com.cma.pojo.User;
4
5 /**
6 * 用户DAO
7 */
8 public interface UserDao {
9 /**
10 * 根据用户ID 获取用户对象
11 * @param userid 用户ID
12 * @return
13 * @throws Exception
14 */
15 public User findUserById(Integer userid)throws Exception;
16 }
4. 在resources下创建database.properties 数据库连接配置文件
1 driver=com.mysql.jdbc.Driver
2 #在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8
3 url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
4 user=root
5 password=root
5. 编写映射文件UserMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <!-- namespace:命名空间 作用==接口实现类(UserDao接口的路径)-->
6 <mapper namespace="com.cma.dao.UserDao">
7 <!--
8 id 接口方法名
9 parameterType 参数类型 不是必须的
10 resultType 返回数据类型(完全限定名)
11 -->
12 <select id="findUserById" parameterType="int"
13 resultType="com.cma.pojo.User">
14 select
15 id,
16 userCode,
17 userName,
18 userPassword,
19 birthday,
20 gender from smbms_user where id =#{userid}
21 </select>
22 </mapper>
6. 编写核心文件mybatis.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration
3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6 <!--读取properties配置文件-->
7 <properties resource="database.properties"></properties>
8
9 <!--创建数据源 default默认加载哪个数据源-->
10 <environments default="csDataSource">
11 <!--可以创建多个数据源 获取数据库连接-->
12 <environment id="csDataSource">
13 <!--事务 JDBC方式加载事务-->
14 <transactionManager type="JDBC"></transactionManager>
15 <!--数据源
16 type属性、其有三种取值:
17 POOLED:使用Mybatis自带的数据库连接池来管理数据库连接
18 UNPOOLED:不使用任何数据库连接池来管理数据库连接
19 JNDI:jndi形式使用数据库连接、主要用于项目正常使用的时候
20 -->
21 <dataSource type="POOLED">
22 <property name="driver" value="${driver}"/>
23 <property name="url" value="${url}"/>
24 <property name="username" value="${user}"/>
25 <property name="password" value="${password}"/>
26 </dataSource>
27 </environment>
28 </environments>
29 <!--扫描mapper文件-->
30 <mappers>
31 <mapper resource="mappers/UserMapper.xml"></mapper>
32 </mappers>
33 </configuration>
7. 编写测试类
1 import com.cma.dao.UserDao;
2 import com.cma.pojo.User;
3 import org.apache.ibatis.io.Resources;
4 import org.apache.ibatis.session.SqlSession;
5 import org.apache.ibatis.session.SqlSessionFactory;
6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
7 import org.junit.Test;
8 import java.io.InputStream;
9
10 public class UserDaoTest {
11 @Test
12 public void findUserById() {
13 try {
14 InputStream is = Resources.getResourceAsStream("mybatis.xml");
15 //将is流转换为 sqlSessionFactory 工厂类
16 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
17 //打开数据库连接
18 /**
19 * true 自动提交 (默认)
20 * false 关闭自动提交
21 */
22 SqlSession sqlSession = sqlSessionFactory.openSession(true);
23 //指定加载哪个mapper 实例化类
24 UserDao userDao = sqlSession.getMapper(UserDao.class);
25 User user = userDao.findUserById(1);
26 System.out.println(user.toString());
27 //释放资源
28 sqlSession.close();
29 } catch (Exception e) {
30 e.printStackTrace();
31 }
32 }
33 }