mybatis plus 根据表名获得实体
时间: 2023-06-16 16:02:37 浏览: 631
mybatis_plus学习代码从入门到精通.rar
在 MyBatis Plus 中,可以通过 `SqlRunner` 对象执行任意 SQL 语句,因此可以使用 SQL 语句查询表信息,并根据表信息动态构建实体类。以下是一个示例代码:
```java
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TableHelper {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "root";
private static final String PASSWORD = "root";
/**
* 根据表名获取实体类名
*
* @param tableName 表名
* @return 实体类名
*/
public static String getEntityNameByTableName(String tableName) {
String entityName = StringUtils.toCamelCase(tableName);
return StringUtils.capitalize(entityName);
}
/**
* 根据表名获取实体类
*
* @param tableName 表名
* @return 实体类
*/
public static Class<?> getEntityClassByTableName(String tableName) throws ClassNotFoundException {
String entityName = getEntityNameByTableName(tableName);
String className = "com.example.entity." + entityName;
return Class.forName(className);
}
/**
* 根据表名获取表信息
*
* @param tableName 表名
* @return 表信息
*/
public static TableInfo getTableInfoByTableName(String tableName) throws SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
TableInfo tableInfo = new TableInfo();
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
stmt = conn.createStatement();
String sql = "SHOW FULL COLUMNS FROM " + tableName;
rs = stmt.executeQuery(sql);
while (rs.next()) {
String fieldName = StringUtils.toCamelCase(rs.getString("Field"));
String fieldComment = rs.getString("Comment");
tableInfo.addFieldInfo(new FieldInfo(fieldName, fieldComment));
}
tableInfo.setTableName(tableName);
tableInfo.setEntityClass(getEntityClassByTableName(tableName));
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
return tableInfo;
}
}
```
使用示例:
```java
TableInfo tableInfo = TableHelper.getTableInfoByTableName("user");
Class<?> entityClass = tableInfo.getEntityClass();
```
其中 `TableInfo` 类和 `FieldInfo` 类是自定义的类,分别用于保存表信息和字段信息。
阅读全文