java开发

技术学习笔记

springboot整合mybatis入门

第一步:导入相关包

 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency> 

第二步:定义数据操作接口

@Mapper
public interface UserMapper {
    User findUserById(int id);
    @Insert("insert into user(username,password) values(#{username},#{password})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    int insertUser(User user);
    int insertUserById(User user);
} 

这里如果加上@Mapper标签 那么主文件

Application
里就不用添加@mappsacan 否则需要入口文件添加统一的扫描文件路径


@MapperScan("com.example.mybtis.mapper")
public class MybtisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybtisApplication.class, args);
    }
}
 

具体操作方法可以通过@Select @Insert等标签通过写SQL语句完成也可以定制配置文件

第四步:定义配置文件

<?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.example.mybtis.mapper.UserMapper">
    <select  id="findUserById" resultType="com.example.mybtis.entity.User">
        select * from user where id = #{id}
    </select>
    <!--添加订单到order-->
    <insert id="insertUserById" parameterType="com.example.mybtis.entity.User">
        <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
            select LAST_INSERT_ID()
        </selectKey>
        insert into user(username,password)
        values(#{username},#{password})
    </insert>
</mapper> 


注意:定义了配置文件那么配置里需要定义好mapp文件的路径如:

mybatis.mapper-locations= classpath:mapping/**.xml 

发表评论:

Powered By Z-BlogPHP 1.7.1

唐云飞个人日记