mybatis mysql獲取當前資料庫所有表與表字段資訊
阿新 • • 發佈:2019-01-29
最近在做一個程式碼生成器,所以就需要獲取到當前表結構資訊,於是搜尋了些相關資料並結合mybatis整理了這篇文章,程式碼相對簡單。
1、編寫一個Mapper介面 程式碼如下:
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; @Mapper public interface TableDao { @Select("select * from information_schema.TABLES where TABLE_SCHEMA=(select database())") List<Map> listTable(); @Select("select * from information_schema.COLUMNS where TABLE_SCHEMA = (select database()) and TABLE_NAME=#{tableName}") List<Map> listTableColumn(String tableName); }
2、開始使用(確保TableDao能被掃描注入到)
import cn.ffast.core.annotations.ApiDoc; import cn.ffast.core.vo.ServiceRowsResult; importcn.ffast.generator.dao.TableDao; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController @RequestMapping("/api/generator/table") public class TableController { @Resource TableDao tableDao; @ApiDoc(name = "資料表列表", description = "") @RequestMapping("/list") public ServiceRowsResult list(String id) { ServiceRowsResult result = new ServiceRowsResult(true); result.setPage(tableDao.listTable()); return result; } @ApiDoc(name = "資料表結構", description = "") @RequestMapping("/columns") public ServiceRowsResult info(String tableName) { ServiceRowsResult result = new ServiceRowsResult(true); result.setPage(tableDao.listTableColumn(tableName)); return result; } }
執行結果