在实习的快结束的时候,看到开发写的一个接口,利用客户端模式获取token后,可以选择的拿到一些基本表的部分信息,自己无聊学着练习写一个。
我使用的是SpringBoot+MyBatils-Plus,Dao层的Mapper类我使用的是xml映射。
这是Dao层的代码
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component("DateFromTableDao")
public interface DateFromTableMapper {
List<Map<String, Object>> getDateFromTable(String tableName);
}
这是xml映射的代码,第一次练习的情况下只提供了两个表可以选择,但是在实际中作为一个接口也不会有太多的基础表的信息提供给第三方抓取,所以我直接是SELECT * ,实际是我们可以只给出部分的字段,然后这里我是所以<choose>分辨入参表名对应的SQL语句,不需要在Controller中所以if-else去判断。
<?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.liang.Dao.DateFromTableMapper">
<select id="getDateFromTable" resultType="java.util.Map">
<choose>
<when test="tableName == 'title'">
SELECT * FROM title
</when>
<when test="tableName == 'treatment'">
SELECT * FROM treatment
</when>
</choose>
</select>
</mapper>
这是Service层的代码
import java.util.List;
import java.util.Map;
public interface DateFromTableService {
List<Map<String, Object>> getDateFromTable(String tableName);
}
这是Service实现层的代码
import com.example.liang.Dao.DateFromTableMapper;
import com.example.liang.Service.DateFromTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Service
public class DateFromTableServiceImpl implements DateFromTableService {
@Autowired
private DateFromTableMapper dateFromTableDao;
@Override
public List<Map<String, Object>> getDateFromTable(String tableName) {
return dateFromTableDao.getDateFromTable(tableName);
}
}
这是Controller层的代码,这里是简单的GetMapping接口类型,简单地对入参判断是否为空后再进行小写转换(这个看个人的数据库的情况吧,如果是我实习公司的数据库是BSC_为前缀的话,转换后拼接一下就好了),后面加了一个没有什么用的结果为空的异常,如果改进的话,可以先统一异常处理一下。
import com.example.liang.Service.DateFromTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@Api(tags = {""})
@RestController
@RequestMapping("/api")
public class DateFromTableController {
@Resource
private DateFromTableService dateFromTableService;
@ApiOperation(value = "查询表的部分信息")
@GetMapping("/getDateFromTable")
public List<Map<String, Object>> getDateFromTable(String tableName){
System.out.println("tableName:"+tableName);
if (tableName == null || tableName.trim().isEmpty()) {
throw new IllegalArgumentException("tableName不可为空!");
}
List<Map<String,Object>> results = dateFromTableService.getDateFromTable(tableName.toLowerCase(Locale.ROOT));
if (results == null || results.isEmpty()) {
// 这里可以根据需求返回一个适当的响应或抛出异常
throw new RuntimeException("结果为空: " + tableName);
}
return results;
}
}
希望后面的时候有心情改进一下吧