没什么好介绍这个框架的,一款半自动化sql的关系映射框架,之所以会写这篇文章还是为了标注一下自己在写CRUD操作过程中的一些思考和理解。
jar包所依赖的信息
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
userMapper文件信息:
<?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.wpw.mybatis.mapper.UserMapper"> <resultMap id="userResultMap" type="com.wpw.mybatis.entity.User"> <id property="id" column="id"/> <result property="userName" column="user_name"/> <result property="userAge" column="user_age"/> <result property="userAddress" column="user_address"/> </resultMap> <select id="selectUserById" parameterType="int" resultMap="userResultMap"> select * from user where id = #{id} </select>
<select id="selectUser" parameterType="string" resultMap="userResultMap"> select * from user where user_name = #{userName} </select> <select id="selectUserByName" parameterType="string" resultMap="userResultMap"> select * from user where user_name = #{userName} </select> <!--执行insert方法,useGeneratedKeys设置为"true"表明要mybatis获取由数据库自动生成的主键; keyProperty="id" 指定把获取到的主键值注入到User的id属性--> <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(user_name, user_age, user_address) values (#{userName}, #{userAge}, #{userAddress}); </insert>
<update id="update" parameterType="User" useGeneratedKeys="true" keyProperty="id"> update user set user_name=#{userName}, user_age=#{userAge}, user_address=#{userAddress} where id = #{id} </update> <delete id="delete" parameterType="int" > delete from user where id = #{id} </delete></mapper>
UserMapper接口所提供的方法。
package com.wpw.mybatis.mapper;
import com.wpw.mybatis.entity.User;
import java.util.List;
/** * @author wpw */public interface UserMapper { /** * 根据用户id查找用户信息 * * @param id 用户id * @return user */ User selectUserById(Integer id);
/** * 根据用户名称查询用户列表信息 * * @param userName 用户名称 * @return userList列表 */ List<User> selectUserByName(String userName);
/** * 保存用户信息 * * @param user 用户信息 * @return 自增主键 */ int insert(User user);
/** * 更新用户信息 * * @param user 用户信息 * @return 主键 */ int update(User user);
/** * 删除用户信息 * * @param id 用户id */ void delete(Integer id);}
实体类信息:
package com.wpw.mybatis.entity;
import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor;import lombok.experimental.Accessors;
import java.io.Serializable;
/** * 用户类 * * @author wpw */@AllArgsConstructor@NoArgsConstructor@Data@Builder@Accessors(chain = true)public class User implements Serializable { private Integer id; private String userName; private Integer userAge; private String userAddress;}
Configuration.xml文件信息,记得放到resources文件夹下即classpath下:
<?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> <!-- mybatis别名定义 --> <typeAliases> <typeAlias alias="User" type="com.wpw.mybatis.entity.User"/> </typeAliases>
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/springboot?serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments>
<!-- mybatis的mapper文件,每个xml配置文件对应一个接口 --> <mappers> <mapper resource="com/wpw/mybatis/mapper/UserMapper.xml"/> </mappers></configuration>
基于单元测试进行编写增删改查示例程序。
package com.wpw.mybatis;
import com.wpw.mybatis.entity.User;import com.wpw.mybatis.mapper.UserMapper;import jdk.nashorn.internal.ir.annotations.Ignore;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 org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;import java.io.InputStream;import java.util.List;import java.util.Objects;import java.util.Optional;
@SpringBootTestclass MybatisApplicationTests { private static SqlSessionFactory sqlSessionFactory; private static InputStream inputStream;
static { try { inputStream = Resources.getResourceAsStream("Configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } }
public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; }
@Test @Ignore public void testSearchUserById() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUserById(1); System.out.println("user = " user); } finally { sqlSession.close(); } }
@Test @Ignore public void testSearchUserListByUserName() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> userList = userMapper.selectUserByName("test1"); userList.stream().filter(Objects::nonNull).forEach(x -> { System.out.println("x = " x); }); } finally { sqlSession.close(); } }
@Test @Ignore public void update() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int update = userMapper.update(User.builder().build().setId(1).setUserName("ceShi").setUserAge(10).setUserAddress("hangzhou")); System.out.println("update = " update); //默认不提交事务,需手动提交事务 sqlSession.commit(); } finally { sqlSession.close(); }
}
@Test @Ignore public void insert() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int insert = userMapper.insert(User.builder().build().setUserName("zhangSan").setUserAge(10).setUserAddress("hangzhou")); System.out.println("insert = " insert); //默认不提交事务,需要手动提交 sqlSession.commit(); } finally { sqlSession.close(); }
}
@Test public void delete() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.delete(7); //默认不自动提交事务,需要手动提交 sqlSession.commit(); } finally { sqlSession.close(); } }
@Test void contextLoads() { }
}
整个项目的结构图
到这里就结束了Mybatis的部分理解过程,这一篇不是一篇很好看的文章,只是为了自己去理解一下这个过程做个总结而已。