springboot整合mybatis

1.引入mybatis-springboot,jdbc和mysql依赖

     
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2.配置文件中配置数据库并整合mybatis

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:33060/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver


# 整合mybatis
mybatis:
  # 配置别名
  type-aliases-package: com.kuang.springbootmybatis.pojo
  # 配置映射的xml文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml

3.实体类User,此处使用了lombok

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String username;
    private Date birthday;
    private char sex;
    private String address;
}

4.mapper类UserMapper,类上添加注解@Mapper,即可注入到mybatis中

在启动类上添加注解@MapperScan("包名")可以对包下的所有mapper进行扫描 @MapperScan和@Mapper二者取一即可
@Mapper
@Repository
public interface UserMapper {

    List<User> getUsers();

    User getUserById(int id);

    int addUser(User user);

    int deleteUser(int id);

    int updateUser(User user);
}

5.在配置文件的mapper-locations: classpath:mybatis/mapper/*.xml的位置编写UserMapper.xml

<?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.kuang.springbootmybatis.mapper.UserMapper">

    <select id="getUsers" resultType="User">
        select * from user
    </select>

    <select id="getUserById" resultType="User">
        select * from user where id = #{id}
    </select>

    <insert id="addUser" parameterType="User">
        insert into user (id,username) values (#{id},#{username})
    </insert>

    <update id="updateUser" parameterType="User">
        update user set username=#{username} where id=#{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>

</mapper>

非常的简单,导入依赖,配置好数据库连接语句和xml文件的位置后,只要添加注解就可以直接用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值