个人主页: 叶落闲庭
我的专栏:
c语言
数据结构
javaEE
操作系统
Redis
石可破也,而不可夺坚;丹可磨也,而不可夺赤。
MyBatisPlus官方提供了starter,其中集成了Mybatis和MybatisPlus的所有功能,并且实现了自动装配效果。
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.2version>
dependency>
public interface UserMapper extends BaseMapper<User> {
}
create table user
(
id int not null primary key,
account int null
);
public interface UserMapper {
int insert(User row);
int insertSelective(User row);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User row);
int updateByPrimaryKey(User row);
}
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.demo.po.User">
resultMap>
<sql id="Base_Column_List">
id, account
sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
select>
<insert id="insert" parameterType="com.demo.po.User">
insert into user (id, account)
values (#{id,jdbcType=INTEGER}, #{account,jdbcType=INTEGER})
insert>
<insert id="insertSelective" parameterType="com.demo.po.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
if>
<if test="account != null">
account,
if>
trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
if>
<if test="account != null">
#{account,jdbcType=INTEGER},
if>
trim>
insert>
<update id="updateByPrimaryKeySelective" parameterType="com.demo.po.User">
update user
<set>
<if test="account != null">
account = #{account,jdbcType=INTEGER},
if>
set>
where id = #{id,jdbcType=INTEGER}
update>
<update id="updateByPrimaryKey" parameterType="com.demo.po.User">
update user
set account = #{account,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
update>
mapper>
public interface UserMapper extends BaseMapper<User> {
}
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void testInsert() {
User user = new User();
user.setId(5);
user.setAccount(2000);
userMapper.insert(user);
}
@Test
void testSelectById() {
User user = userMapper.selectById(5);
System.out.println(user);
}
@Test
void testUpdateById() {
User user = new User();
user.setId(5);
user.setAccount(8000);
userMapper.updateById(user);
}
@Test
void testDeleteById() {
userMapper.deleteById(5);
}
}
MyBatisPlus:通过扫描实体类,并基于反射获取实体类信息作为数据库表信息。
MyBatisPlus官网:https://www.baomidou.com/pages/223848/#tablename
MyBatisPlus中的配置大都是默认配置好的,我们使用的时候基本不用修改大量的配置,除非遇到特殊的情况需要设置一些配置,可以参考MyBatisPlus的官方文档进行修改。
mybatis-plus:
type-aliases-package: com.demo.po
mapper-locations: classpath*:mapper/**/*.xml # 默认
global-config:
db-config:
id-type: auto # id类型自增长