Home Mybatis学习 Springboot整合Mybatis

Springboot整合Mybatis

1.导入依赖(Mybatis)

<!--        mybatis自带的-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

2.编写配置文件连接数据库(application.properties)
spring.datasource.username=root
spring.datasource.password=123456789
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

以下为具体测试:

3.编写实体类(Pojo)

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}
4.IDEA连接数据库

5.实体类写好编写Mapper接口

或者
6.在Mapper.xml中编写sql语句
<mapper namespace="com.yang.dao.UserMapper">

    <select id="getUserList" resultType="PoJo.User">
        select * from mysql.mybatisuser
    </select>

    <select id="getUserLike" parameterType="map" resultType="PoJo.User">
        select * from mysql.mybatisuser where name like #{value};
    </select>


    <select id="getUserById" parameterType="int" resultType="PoJo.User">
        select * from mysql.mybatisuser where id = #{userid};
    </select>

    <select id="getUserById2" parameterType="map" resultType="PoJo.User">
        select * from mysql.mybatisuser where id = #{id};
    </select>

    <insert id="addUser" parameterType="PoJo.User">
        insert into mysql.mybatisuser (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
<!--    <insert id="addUser2" parameterType="map">-->
<!--        insert into mysql.mybatisuser (id,name,pwd) values (#{userid},#{username},#{password});-->
<!--    </insert>-->
    <update id="updateUser" parameterType="PoJo.User">
        update mysql.mybatisuser set name = #{name},pwd = #{pwd} where id = #{id};
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from mysql.mybatisuser where id = #{id};
    </delete>
</mapper>

7.Springboot整合Mybatis
#整合Mybatis
mybatis.type-aliases-package=com.yang.pojo   //包下实体类起别名
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml    //Mapper的地址
其他配置也写在这里

8.编写Controller,调用Dao层(Mapper接口)
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("userList")
    public List<User> queryUserList(){
        List<User> userList = userMapper.queryUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        return userList;
    }
}

SIMILAR ARTICLES

发表评论

发表评论