SpringBoot整合Mybatis-plus操作数据库

SpringBoot整合Mybatis-plus操作数据库

    • 1.在pom.xml文件中引入依赖
    • 2.在application.yml文件中配置数据库连接
    • 3.修改实体类AdChannel代码
    • 4.创建mapper
    • 5.创建service接口和serviceImpl
    • 6.编写Controller代码
    • 7.启动类中进行配置

1.在pom.xml文件中引入依赖

<!-- mybatis相关 -->
        <!-- mysql驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!-- mybatis-plus依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>

2.在application.yml文件中配置数据库连接

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
# 设置Mapper接口所对应的XML文件位置,如果你在Mapper接口中有自定义方法,需要进行该配置
mybatis-plus:
  # 设置映射文件扫描
  mapper-locations: classpath*:mybatis/*.xml
  # 设置别名包扫描路径,通过该属性可以给包中的类注册别名
  type-aliases-package: com.learn.quick.pojos

3.修改实体类AdChannel代码

@Data  //lombok注解,通过lombok构建属性的set/get方法
@TableName("ad_channel")  //标识实体类和数据库表的对应关系
public class AdChannel{

    @TableId(value = "id",type = IdType.AUTO) //标识实体类属性和数据库表主键的对应关系
    private Integer id;

    @TableField(value = "name") //标识实体类属性和数据库表字段对应关系
    private String name;

    @TableField(value = "description")
    private String description;

    @TableField(value = "is_default")
    private Boolean isDefault;

    @TableField(value = "status")
    private Boolean status;

    @TableField(value = "ord")
    private Integer ord;

    @TableField(value = "created_time")
    private Date createdTime;

}

4.创建mapper

@Mapper
public interface QuickStartMapper  extends BaseMapper<AdChannel> {
}

5.创建service接口和serviceImpl

public interface QuickStartService extends IService<AdChannel> {

@Service
public class QuickStartServiceImpl extends ServiceImpl<QuickStartMapper, AdChannel> implements QuickStartService {

}

6.编写Controller代码

@RestController
@RequestMapping("/quickstart")
public class QuickStartController {

    @Autowired
    private QuickStartService quickStartService;

    @RequestMapping("/show")
    public AdChannel show(){

        AdChannel adChannel = quickStartService.getById(1);

        return adChannel;
    }

}

7.启动类中进行配置

@SpringBootApplication
@MapperScan("com.learn.quick.mapper")
public class SpringbootQuickstartApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootQuickstartApplication.class, args);
    }
}

你可能感兴趣的:(JavaLearn,spring,boot,java,mysql)