SpringBoot新增配置Mybatis

修改pom.xml,新增Mybatis、数据库相关的依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

在application.properties文件中配置Mybatis连接信息

mybatis.type-aliases-package=com.example.demo
#mysql驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#远程数据库链接 serverTimezone不可少
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
#MySQL数据库用户名、密码
spring.datasource.username=root
spring.datasource.password=xxxxx
#xml格式的mapper文件位置
mybatis.mapper-locations=classpath:/mapper/*.xml

添加mapper接口对应的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.example.demo.mapper.TestMapper">
   
    <select id="selectlist" resultType="java.util.Map">
        SELECT
  (SELECT count(*) FROM nf_objects) zs,
  (SELECT count(*) FROM nf_objects where obj_online=1) zx,
  (SELECT count(*) FROM nf_objects where obj_online!=1) lx
    </select>
  
</mapper>

controller代码文件

package com.example.demo.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.mapper.TestMapper;

@Controller
@RequestMapping("/test")
public class TestController {

@Autowired
    private TestMapper testMapper;

@ResponseBody
@GetMapping()
    public String objectsaddress()
    {
  Map<Integer,Integer> dd = testMapper.selectlist();
        return "";
    }
}

TestMapper文件内容

package com.example.demo.mapper;

import java.util.Map;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TestMapper
{
  
public Map<Integer,Integer> selectlist();
}
正在加载评论...