让我来讲解一下如何让Java只根据数据库表名自动生成实体类的完整攻略。
1. 创建Maven工程
首先,我们需要创建一个Maven工程,用于管理我们的项目依赖和构建。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>auto-generate-entity</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
</project>
2. 连接数据库
我们需要通过Java代码连接到数据库,然后获取数据库中的表名。
public class DatabaseUtil {
private static final String URL = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=Asia/Shanghai";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
public static Set<String> getTableNames() {
Set<String> tableNames = new HashSet<>();
try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
ResultSet rs = connection.getMetaData().getTables(null, null, null, null)) {
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return tableNames;
}
}
3. 自动生成实体类
接下来,我们可以根据表名自动生成实体类了。
public class EntityGenerator {
private static final String PACKAGE_NAME = "com.example.entity";
private static final String FILE_PATH = "src/main/java/com/example/entity/";
public static void generate() {
Set<String> tableNames = DatabaseUtil.getTableNames();
for (String tableName : tableNames) {
try (PrintWriter writer = new PrintWriter(FILE_PATH + tableName + ".java")) {
writer.println("package " + PACKAGE_NAME + ";");
writer.println();
writer.println("public class " + tableName + " {");
try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM " + tableName + " LIMIT 1")) {
ResultSetMetaData metaData = rs.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnName(i);
String columnClassName = metaData.getColumnClassName(i);
int dotIndex = columnClassName.lastIndexOf(".");
String columnType = columnClassName.substring(dotIndex + 1);
writer.println(" private " + columnType + " " + toCamelCase(columnName) + ";");
}
writer.println("}");
writer.flush();
}
} catch (SQLException | FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static String toCamelCase(String s) {
StringBuilder sb = new StringBuilder();
boolean capitalizeNext = false;
for (char c : s.toCharArray()) {
if (c == '_') {
capitalizeNext = true;
} else {
if (capitalizeNext) {
sb.append(Character.toUpperCase(c));
capitalizeNext = false;
} else {
sb.append(c);
}
}
}
return sb.toString();
}
}
上述代码通过遍历数据库中的所有表名,然后循环获取每个表的列信息,生成相应的实体类。实体类的命名规则为表名的驼峰命名方式。
假设我们的数据库有一张表名为user_info
,则生成的实体类为:
package com.example.entity;
public class user_info {
private Long id;
private String name;
private String gender;
private Integer age;
// 省略 getter/setter
}
示例1
假设我们的数据库有两张表,分别为user_info
和order_info
,我们可以通过如下代码生成对应的实体类:
public static void main(String[] args) {
EntityGenerator.generate();
}
这段代码执行后,会在项目的src/main/java/com/example/entity/
目录下生成两个Java文件,分别为user_info.java
和order_info.java
。
示例2
假设我们的实体类需要扩展,为所有实体类添加一个公共的BaseEntity
,我们可以修改EntityGenerator
类,修改后的代码如下:
public class EntityGenerator {
private static final String PACKAGE_NAME = "com.example.entity";
private static final String FILE_PATH = "src/main/java/com/example/entity/";
private static final String BASE_IMPORT = "com.example.entity.BaseEntity";
public static void generate() {
// 省略前面的代码
for (String tableName : tableNames) {
try (PrintWriter writer = new PrintWriter(FILE_PATH + tableName + ".java")) {
writer.println("package " + PACKAGE_NAME + ";");
writer.println();
writer.println("import " + BASE_IMPORT + ";");
writer.println();
writer.println("public class " + tableName + " extends BaseEntity {");
// 省略后面的代码
} catch (SQLException | FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
在生成实体类时添加了一个基础类BaseEntity
的继承关系,之后我们只需要在BaseEntity
类中添加一些公共的属性和方法,即可为所有实体类提供基础功能。
关于一些细节处理,代码中已包含注释。希望对你有所帮助,如有疑问欢迎继续咨询。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:如何让java只根据数据库表名自动生成实体类 - Python技术站