MyBatis是什么以及为什么需要ORM框架、快速搭建
MyBatis是什么
MyBatis的前身是Ibatis,本质是一款半自动化的ORM框架,除了能对POJO进行ORM映射之外,还可以编写SQL脚本语句。主要是为了解决我们平时开发中经常写的JDBC代码,将繁琐的JDBC代码封装起来,化繁为简。
MyBatis映射文件 四要素:
1.SQL语句
2.映射规则
3.POJO
4.Mapper接口
为什么需要 ORM 框架?**
传统的 JDBC 编程存在的弊端:
1.工作量大,操作数据库至少要 5 步;
2.业务代码和技术代码耦合;
3.连接资源手动关闭,带来了隐患;
MyBatis 快速入门
步骤如下:
- 加入 mybatis 的依赖,版本 3.5.x
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!-- mybatis相关依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0-SNAPSHOT</version>
<!-- <version>3.4.1</version> -->
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
- 添加 mybatis 的配置文件,包括 MyBatis 核心文件和 mapper.xml 文件
<properties resource="db.properties" />
<settings>
<!-- 设置自动驼峰转换 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
<!-- 开启懒加载 -->
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。默认:true -->
<setting name="aggressiveLazyLoading" value="false" />
</settings>
<!-- 别名定义 -->
<typeAliases>
<package name="com.enjoylearning.mybatis.entity" />
</typeAliases>
<!--配置environment环境 -->
<environments default="development">
<!-- 环境配置1,每个SqlSessionFactory对应一个环境 -->
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="UNPOOLED">
<property name="driver" value="${jdbc_driver}" />
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
</dataSource>
</environment>
</environments>
<!-- 映射文件,mapper的配置文件 -->
<mappers>
<!--直接映射到相应的mapper文件 -->
<mapper resource="sqlmapper/TUserMapper.xml" />
</mappers>
-
场景介绍:基于 t_user 表单数据查询、多数据查询;
-
编写实体类、mapper 接口以及 mapper xml 文件;
一、Mapper.xml
<select id="selectByPrimaryKey" resultType="TUser">
select
id, userName, realName, sex, mobile, email, note
from t_user
where id = #{id,jdbcType=INTEGER}
</select>
<select id="selectAll" resultType="TUser">
select
id, userName, realName, sex, mobile, email, note
from t_user
</select>
<resultMap id="UserResultMap" type="TUser" autoMapping="true">
<id column="id" property="id" />
<result column="userName" property="userName"/>
<result column="realName" property="realName" />
<result column="sex" property="sex" />
<result column="mobile" property="mobile" />
<result column="email" property="email" />
<result column="note" property="note" />
<association property="position" javaType="TPosition" columnPrefix="post_">
<id column="id" property="id"/>
<result column="name" property="postName"/>
<result column="note" property="note"/>
</association>
</resultMap>
<select id="selectTestResultMap" resultMap="UserResultMap" >
select
a.id,
userName,
realName,
sex,
mobile,
email,
a.note,
b.id post_id,
b.post_name,
b.note post_note
from t_user a,
t_position b
where a.position_id = b.id
</select>
<resultMap id="BaseResultMap" type="TUser">
<!-- <constructor> <idArg column="id" javaType="int"/> <arg column="userName"
javaType="String"/> </constructor> -->
<id column="id" property="id" />
<result column="userName" property="userName" />
<result column="realName" property="realName" />
<result column="sex" property="sex" />
<result column="mobile" property="mobile" />
<result column="email" property="email" />
<result column="note" property="note" />
</resultMap>
<sql id="Base_Column_List">
id, userName, realName, sex, mobile, email, note,
position_id
</sql>
<resultMap id="userAndPosition1" extends="BaseResultMap" type="TUser">
<association property="position" javaType="TPosition" columnPrefix="post_">
<id column="id" property="id"/>
<result column="name" property="postName"/>
<result column="note" property="note"/>
</association>
</resultMap>
<resultMap id="userAndPosition2" extends="BaseResultMap" type="TUser">
<association property="position" fetchType="lazy" column="position_id" select="com.enjoylearning.mybatis.mapper.TPositionMapper.selectByPrimaryKey" />
</resultMap>
<select id="selectUserPosition1" resultMap="userAndPosition1" >
select
a.id,
userName,
realName,
sex,
mobile,
email,
a.note,
b.id post_id,
b.post_name,
b.note post_note
from t_user a,
t_position b
where a.position_id = b.id
</select>
<select id="selectUserPosition2" resultMap="userAndPosition2" >
select
a.id,
a.userName,
a.realName,
a.sex,
a.mobile,
a.position_id
from t_user a
</select>
<resultMap id="userAndJobs1" extends="BaseResultMap" type="TUser">
<collection property="jobs"
ofType="com.enjoylearning.mybatis.entity.TJobHistory" >
<result column="comp_name" property="compName" jdbcType="VARCHAR" />
<result column="years" property="years" jdbcType="INTEGER" />
<result column="title" property="title" jdbcType="VARCHAR" />
</collection>
</resultMap>
<resultMap id="userAndJobs2" extends="BaseResultMap" type="TUser">
<collection property="jobs" fetchType="lazy" column="id"
select="com.enjoylearning.mybatis.mapper.TJobHistoryMapper.selectByUserId" />
</resultMap>
<select id="selectUserJobs1" resultMap="userAndJobs1">
select
a.id,
a.userName,
a.realName,
a.sex,
a.mobile,
b.comp_name,
b.years,
b.title
from t_user a,
t_job_history b
where a.id = b.user_id
</select>
<select id="selectUserJobs2" resultMap="userAndJobs2">
select
a.id,
a.userName,
a.realName,
a.sex,
a.mobile
from t_user a
</select>
<resultMap id="userAndHealthReportMale" extends="userAndHealthReport" type="TUser">
<collection property="healthReports" column="id"
select= "com.enjoylearning.mybatis.mapper.THealthReportMaleMapper.selectByUserId"></collection>
</resultMap>
<resultMap id="userAndHealthReportFemale" extends="userAndHealthReport" type="TUser">
<collection property="healthReports" column="id"
select= "com.enjoylearning.mybatis.mapper.THealthReportFemaleMapper.selectByUserId"></collection>
</resultMap>
<resultMap id="userAndHealthReport" extends="BaseResultMap" type="TUser">
<discriminator column="sex" javaType="int">
<case value="1" resultMap="userAndHealthReportMale"/>
<case value="2" resultMap="userAndHealthReportFemale"/>
</discriminator>
</resultMap>
<select id="selectUserHealthReport" resultMap="userAndHealthReport">
select
<include refid="Base_Column_List" />
from t_user a
</select>
<resultMap type="TUser" id="userRoleInfo" extends="BaseResultMap">
<collection property="roles" ofType="TRole" columnPrefix="role_">
<result column="id" property="id" />
<result column="Name" property="roleName" />
<result column="note" property="note" />
</collection>
</resultMap>
<select id="selectUserRole" resultMap="userRoleInfo">
select a.id,
a.userName,
a.realName,
a.sex,
a.mobile,
a.note,
b.role_id,
c.role_name,
c.note role_note
from t_user a,
t_user_role b,
t_role c
where a.id = b.user_id AND
b.role_id = c.id
</select>
<select id="selectUserByRoleId" resultMap="userRoleInfo">
select
<include refid="Base_Column_List" />
from t_user a,
t_user_role b
where a.id = b.user_id and
b.role_id = #{id}
</select>
<select id="selectByEmailAndSex1" resultMap="BaseResultMap" parameterType="map">
select
<include refid="Base_Column_List" />
from t_user a
where a.email like CONCAT('%', #{email}, '%') and
a.sex =#{sex}
</select>
<select id="selectByEmailAndSex2" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user a
where a.email like CONCAT('%', #{email}, '%') and
a.sex = #{sex}
</select>
<select id="selectByEmailAndSex3" resultMap="BaseResultMap"
parameterType="com.enjoylearning.mybatis.entity.EmailSexBean">
select
<include refid="Base_Column_List" />
from t_user a
where a.email like CONCAT('%', #{email}, '%') and
a.sex = #{sex}
</select>
<select id="selectBySymbol" resultMap="BaseResultMap">
select
${inCol}
from ${tableName} a
where a.userName = #{userName}
order by ${orderStr}
</select>
<select id="selectIfOper" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user a
where 1=1
<if test="email != null and email != ''">
and a.email like CONCAT('%', #{email}, '%')
</if>
<if test="sex != null ">
and a.sex = #{sex}
</if>
</select>
<select id="selectIfandWhereOper" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user a
<where>
<if test="email != null and email != ''">
and a.email like CONCAT('%', #{email}, '%')
</if>
<if test="sex != null ">
and a.sex = #{sex}
</if>
</where>
</select>
<select id="selectChooseOper" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user a
<where>
<choose>
<when test="email != null and email != ''">
and a.email like CONCAT('%', #{email}, '%')
</when>
<when test="sex != null">
and a.sex = #{sex}
</when>
<otherwise>
and 1=1
</otherwise>
</choose>
</where>
</select>
<update id="updateIfOper" parameterType="TUser">
update t_user
set
<if test="userName != null">
userName = #{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
realName = #{realName,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=TINYINT},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="note != null">
note = #{note,jdbcType=VARCHAR}
</if>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateIfAndSetOper" parameterType="TUser">
update t_user
<set>
<if test="userName != null">
userName = #{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
realName = #{realName,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=TINYINT},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="note != null">
note = #{note,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<insert id="insertIfOper" parameterType="TUser">
insert into t_user (
<if test="id != null">
id,
</if>
<if test="userName != null">
userName,
</if>
<if test="realName != null">
realName,
</if>
<if test="sex != null">
sex,
</if>
<if test="mobile != null">
mobile,
</if>
<if test="email != null">
email,
</if>
<if test="note != null">
note
</if>
)
values(
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
#{realName,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=TINYINT},
</if>
<if test="mobile != null">
#{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="note != null">
#{note,jdbcType=VARCHAR}
</if>
)
</insert>
<select id="selectForeach4In" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user a
where a.userName in
<foreach collection="array" open="(" close=")" item="userName" separator=",">
#{userName}
</foreach>
</select>
<insert id="insertForeach4Batch" useGeneratedKeys="true" keyProperty="id">
insert into t_user (userName, realName,
sex, mobile,email,note,
position_id)
values
<foreach collection="list" separator="," item="user">
(
#{user.userName,jdbcType=VARCHAR},
#{user.realName,jdbcType=VARCHAR},
#{user.sex,jdbcType=TINYINT},
#{user.mobile,jdbcType=VARCHAR},
#{user.email,jdbcType=VARCHAR},
#{user.note,jdbcType=VARCHAR},
#{user.position.id,jdbcType=INTEGER}
)
</foreach>
</insert>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from t_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert1" parameterType="TUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user (id, userName, realName,
sex, mobile,
email,
note, position_id)
values (#{id,jdbcType=INTEGER},
#{userName,jdbcType=VARCHAR},
#{realName,jdbcType=VARCHAR},
#{sex,jdbcType=TINYINT}, #{mobile,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR},
#{note,jdbcType=VARCHAR},
#{position.id,jdbcType=INTEGER})
</insert>
<insert id="insert2" parameterType="TUser">
<selectKey keyProperty="id" order="AFTER" resultType="int">
select
LAST_INSERT_ID()
</selectKey>
insert into t_user (id, userName, realName,
sex, mobile,
email,
note,
position_id)
values (#{id,jdbcType=INTEGER},
#{userName,jdbcType=VARCHAR},
#{realName,jdbcType=VARCHAR},
#{sex,jdbcType=TINYINT}, #{mobile,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR},
#{note,jdbcType=VARCHAR},
#{position.id,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="TUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null">
id,
</if>
<if test="userName != null">
userName,
</if>
<if test="realName != null">
realName,
</if>
<if test="sex != null">
sex,
</if>
<if test="mobile != null">
mobile,
</if>
<if test="email != null">
email,
</if>
<if test="note != null">
note,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
#{realName,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=TINYINT},
</if>
<if test="mobile != null">
#{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="note != null">
#{note,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="TUser">
update t_user
<set>
<if test="userName != null">
userName = #{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
realName = #{realName,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=TINYINT},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="note != null">
note = #{note,jdbcType=VARCHAR},
</if>
<if test="position != null">
position_id = #{position.id,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="TUser">
update t_user
set
userName = #{userName,jdbcType=VARCHAR},
realName =
#{realName,jdbcType=VARCHAR},
sex = #{sex,jdbcType=TINYINT},
mobile =
#{mobile,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
note =
#{note,jdbcType=VARCHAR},
position_id = #{position.id,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
二、实体类
package com.enjoylearning.mybatis.entity;
import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.mysql.jdbc.Blob;
public class TUser implements Serializable{
private Integer id;
private String userName;
private String realName;
private Byte sex;
private String mobile;
private String email;
private String note;
private TPosition position;
private List<TJobHistory> jobs ;
private List<HealthReport> healthReports;
private List<TRole> roles;
@Override
public String toString() {
String positionId= (position == null ? "" : String.valueOf(position.getId()));
return "TUser [id=" + id + ", userName=" + userName + ", realName="
+ realName + ", sex=" + sex + ", mobile=" + mobile + ", email="
+ email + ", note=" + note + ", positionId=" + positionId + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Byte getSex() {
return sex;
}
public void setSex(Byte sex) {
this.sex = sex;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public TPosition getPosition() {
return position;
}
public void setPosition(TPosition position) {
this.position = position;
}
public List<TJobHistory> getJobs() {
return jobs;
}
public void setJobs(List<TJobHistory> jobs) {
this.jobs = jobs;
}
public List<HealthReport> getHealthReports() {
return healthReports;
}
public void setHealthReports(List<HealthReport> healthReports) {
this.healthReports = healthReports;
}
public List<TRole> getRoles() {
return roles;
}
public void setRoles(List<TRole> roles) {
this.roles = roles;
}
public static void main(String[] args) {
System.out.println(1<<2);
}
}
三、Mapper接口
package com.enjoylearning.mybatis.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.enjoylearning.mybatis.entity.EmailSexBean;
import com.enjoylearning.mybatis.entity.TJobHistory;
import com.enjoylearning.mybatis.entity.TUser;
public interface TUserMapper {
TUser selectByPrimaryKey(Integer id);
List<TUser> selectAll();
List<TUser> selectTestResultMap();
List<TUser> selectAllTest();
int deleteByPrimaryKey(Integer id);
int insert1(TUser record);
int insert2(TUser record);
int insertSelective(TUser record);
int updateByPrimaryKeySelective(TUser record);
int updateByPrimaryKey(TUser record);
List<TUser> selectUserPosition1();
List<TUser> selectUserPosition2();
List<TUser> selectUserJobs1();
List<TUser> selectUserJobs2();
List<TUser> selectUserHealthReport();
List<TUser> selectUserRole();
List<TUser> selectByEmailAndSex1(Map<String, Object> param);
List<TUser> selectByEmailAndSex2(@Param("email")String email,@Param("sex")Byte sex);
List<TUser> selectByEmailAndSex3(EmailSexBean esb);
List<TUser> selectBySymbol(@Param("tableName")String tableName,
@Param("inCol")String inCol,
@Param("orderStr")String orderStr,
@Param("userName")String userName);
List<TUser> selectIfOper(@Param("email")String email,@Param("sex")Byte sex);
List<TUser> selectIfandWhereOper(@Param("email")String email,@Param("sex")Byte sex);
List<TUser> selectChooseOper(@Param("email")String email,@Param("sex")Byte sex);
int updateIfOper(TUser record);
int updateIfAndSetOper(TUser record);
int insertIfOper(TUser record);
List<TUser> selectForeach4In(String[] names);
int insertForeach4Batch(List<TUser> users);
}
- 编写实例代码:com.enjoylearning.mybatis.MybatisDemo. quickStart
public class MybatisDemo {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
//--------------------第一阶段---------------------------
// 1.读取mybatis配置文件创SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 1.读取mybatis配置文件创SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
inputStream.close();
}
@Test
// 快速入门
public void quickStart() throws IOException {
//--------------------第二阶段---------------------------
// 2.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取对应mapper
TUserMapper mapper = sqlSession.getMapper(TUserMapper.class);
//--------------------第三阶段---------------------------
// 4.执行查询语句并返回单条数据
TUser user = mapper.selectByPrimaryKey(1);
System.out.println(user);
System.out.println("----------------------------------");
// 5.执行查询语句并返回多条数据
List<TUser> users = mapper.selectAll();
for (TUser tUser : users) {
System.out.println(tUser);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~