一、IDEA 新建项目一个maven 项目
项目结构如下:
image.png
二、引入包
编辑pom.xml
,引入如下的包
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
三、编写配置文件
1、resources
目录下新增 db.properties
文件
数据库连接配置如下
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.109.128:3306/test?serverTimezone=UTC
jdbc.username=mysqluser
jdbc.password=root
2、resources
目录下新增 log4j.properties
文件
配置log4j
日志的输出及格式
log4j.rootLogger=DEBUG , stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
四、数据库建表
表名【role】
image.png
五、编写 Mapper
1、编写 POJO 类 Role
package Entity;
public class Role {
private String id;
private String roleName;
private String note;
public String getId(){return id;}
public void setId(String id){this.id = id;}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String toString(){
return "RoleBean{" +
"id='" + id + '\'' +
",roleName='" + roleName + '\'' +
",note='" + note + '\'' +
"}";
}
}
2、编写 Mapper 类 RoleMapper
package Mapper;
import Entity.Role;
import java.util.List;
public interface RoleMapper {
public int insertRole(Role role);
public int deleteRole(String id) ;
public int updateRole(Role role) ;
public Role getRole( String id) ;
public List<Role> findRoles(String roleName);
}
3、编写 Mapper 配置文件
resources
目录下新增 RoleMapper.xml
文件
<?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="Mapper.RoleMapper">
<insert id="insertRole" parameterType="Entity.Role">
insert into role(id, RoleName, Note) values (#{id}, #{roleName}, #{note})
</insert>
<delete id="deleteRole" parameterType="String">
DELETE from role where id = #{id}
</delete>
<update id="updateRole" parameterType="roleentity">
update role set RoleName = #{roleName) , note= #{note) where id= #{id)
</update>
<select id="getRole" parameterType="string" resultType="roleentity" >
select id, RoleName as roleName, note from role where id = #{id)
</select>
<select id="findRoles" parameterType="string" resultType="roleentity" >
select id, RoleName as roleName, note from role where RoleName like concat('%', #{roleName}, '%')
</select>
</mapper>
注意,其中resultType
需要使用完全限定的类名称,或使用下面config定义的别名
IDEA可以安装插件【MyBatis plugin】,具有检查及提示相关文档配置功能
4、编写 mybatis-config.xml
resources
目录下新增 mybatis-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="db.properties"/> --读取 db.properties 的配置
<typeAliases>
<typeAlias alias="roleentity" type="Entity.Role" /> --定义类型别名
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/> --使用 properties 中配置的属性值
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<mappers>
<mapper resource="mapper/RoleMapper.xml"/>
</mappers>
</configuration>
5、完成后的目录结构
image.png六、编写类SqlSessionFactoryUtil
新增SqlSessionFactoryUtil
类用于维护全局唯一的SqlSessionFactory
,并提供方法返回一个可用的SqlSession
对象
package Utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtil {
private final static Class<SqlSessionFactoryUtil> LOCK = SqlSessionFactoryUtil.class ;
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactoryUtil(){}
public static SqlSessionFactory getSqlSessionFactory(){
synchronized (LOCK){
if(sqlSessionFactory != null){
return sqlSessionFactory;
}
//配置文件
String resource = "mybatis-config.xml";
//配置文件流
InputStream inputStream;
try{
inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
public static SqlSession openSqlSession(){
if(sqlSessionFactory == null){
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
注:使用单例模式
七、编写测试类,插入表数据
新增Test
类,main
方法如下:
public static void main(String[] args){
Logger log = Logger.getLogger(RoleTest.class);
SqlSession sqlSession = null;
try{
sqlSession = SqlSessionFactoryUtil.openSqlSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = new Role();
role.setId(UUIDUtil.newUUIDStrWithoutDash());
role.setRoleName("第一个测试");
role.setNote(DateUtil.getTimeStamp());
//通过sqlSession操作数据库
//sqlSession.insert("Mapper.RoleMapper.insertRole", role);
// 通过 mapper 操作数据库, 更推荐这种方式
roleMapper.insertRole(role);
// 下面这个必须加上,否则不会提交更改到数据库
sqlSession.commit();
log.info(role);
} finally {
if(sqlSession != null){
sqlSession.close();
}
}
}
注:
1、写入数据有以下两种方式
sqlSession.insert("Mapper.RoleMapper.insertRole", role);
或
roleMapper.insertRole(role);
推荐使用第二种
2、默认的自动提交是disable的
image.png所以后面需要加一句代码
sqlSession.commit();
才能真正写入数据到表中
3、sqlSession
使用完需要调用close()
方法释放资源
程序运行后,可以查看表中已有新增的数据:
image.png
八、完整代码
九、TypeHandler 处理 Enum 转换
十、高阶-实现一个用于分页的mybatis
插件
1、新增用于分页的参数POJI类PageParams
image.png
2、Mapper
类新增查询方法,接收参数
public List<Role> findRolesPaged(@Param("pageParams") PageParams pageParams, @Param("roleName") String roleName);
3、Mapper.xml
新增配置
<select id="findRolesPaged" parameterType="string" resultType="roleentity" flushCache="true" useCache="false">
select id, RoleName as roleName, Note as note from role
<where>
<if test="roleName != null">
roleName like concat('%', #{roleName},'%')
</if>
</where>
</select>
4、编写插件类MySqlPageQueryPlugin
,实现接口Interceptor
5、mybatis
配置文件新增插件的使用配置
<plugin interceptor="Utils.MySqlPageQueryPlugin">
<!--默认页码-->
<property name="default.pageNo" value="1"/>
<!--默认每页条数-->
<property name="default.pageSize" value="100"/>
<!--是否启动分页插件功能-->
<property name="default.useFlag" value="true"/>
<!--是否检查页码有效性,如果非有效,则抛出异常-->
<property name="default.checkPageNoLessThanSize" value="false"/>
<!--默认是否清除最后一个 order by 后的语句-->
<property name="default.isCleanOrderBy" value="true"/>
</plugin>
6、编写junit
测试方法
@Test
public void roleMapPageSelect(){
SqlSession sqlSession = SqlSessionFactoryUtil.openSqlSession();
RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
PageParams pageParams = new PageParams();
pageParams.setPageSize(3);
List<Role> roles = mapper.findRolesPaged(pageParams,"test");
logger.warn("Page【1】 select result...............");
for (Role r : roles){
logger.info(r);
}
pageParams.setPageNo(2);
// select mapper 需要同时设置【flushCache="true" useCache="false"】才能不缓存
// 否则下面这个不会再调用数据库查询,而是直接返回上一次缓存的结果
roles = mapper.findRolesPaged(pageParams,"test");
logger.warn("Page【2】 select result...............");
for (Role r : roles){
logger.info(r);
}
sqlSession.close();
}
网友评论