1、自定义注解
(1)FieldInfo.java用于添加列注释等等
package com.peam.web.media.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author 施子安
* @version 1.0
* @date 2023/9/26 16:12
* @Description 自定义列
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldInfo {
String columnName();
String columnType();
/**
* 描述
* @return
*/
String commit();
}
(2)TableNameNew.java用于生成表名字
package com.peam.web.media.annotation;
import javax.validation.constraints.NotNull;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author 施子安
* @version 1.0
* @date 2023/9/26 16:11
* @Description 自定义注解生成表明
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableNameNew {
@NotNull
String value();
}
2、工具类CreateTable.java
package com.peam.web.media;
import com.peam.web.media.annotation.FieldInfo;
import com.peam.web.media.annotation.TableNameNew;
import org.reflections.Reflections;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CreateTable {
public static String createTableByAnnotations() {
TableNameNew annotation = null;
FieldInfo fieldInfo = null;
String str = "";
boolean hasIdField = false; // 添加一个标志位来检测是否存在 id 字段
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/test?characterEncoding=UTF-8",
"root", "123456789");
Statement statement = connection.createStatement();
Reflections reflections = new Reflections("com.peam.web.media");
Set<Class<?>> set = reflections.getTypesAnnotatedWith(TableNameNew.class);
for (Class<?> aClass : set) {
annotation = aClass.getAnnotation(TableNameNew.class);
Field[] f = aClass.getDeclaredFields();
for (Field field : f) {
fieldInfo = field.getAnnotation(FieldInfo.class);
if (fieldInfo != null) {
// 处理字段名
String columnName = field.getName();
// 将大写字母前面有两个或两个以上字符的属性名称转换为下划线分隔,后面大写字母变小写
columnName = columnName.replaceAll("(.)([A-Z]+)", "$1_$2").toLowerCase();
// columnName = columnName.replaceAll(" ", "_");
columnName = columnName.replaceAll("[^a-zA-Z0-9_]", "");
// 处理字段类型,例如 `order` int COMMENT '展示顺序'
String fieldType = fieldInfo.columnType();
fieldType = fieldType.replaceAll("[^a-zA-Z0-9_()]", ""); // 移除非字母、数字、下划线和括号
// 添加字段长度,例如将 varchar(500) 转换为 varchar(500)
Matcher matcher = Pattern.compile("(.+?)\\((\\d+)\\)").matcher(fieldType);
if (matcher.find()) {
String type = matcher.group(1);
int fieldLength = Integer.parseInt(matcher.group(2));
fieldType = type + "(" + fieldLength + ")";
}
str += "`" + columnName + "` " + fieldType + " COMMENT '" + fieldInfo.commit() + "',";
// 检查字段是否为 "id",如果是,则将标志位设置为 true
if (field.getName().equalsIgnoreCase("'id'")) {
hasIdField = true;
}
}
}
statement.execute("DROP TABLE IF EXISTS `" + annotation.value() + "`;");
// 添加主键约束
if (hasIdField) {
statement.execute("CREATE TABLE `" + annotation.value()
+ "` (id INT PRIMARY KEY AUTO_INCREMENT," + str.substring(0, str.length() - 1) + " );");
} else {
statement.execute("CREATE TABLE `" + annotation.value()
+ "` (" + str.substring(0, str.length() - 1) + " );");
}
str = "";
hasIdField = false; // 重置标志位
}
} catch (Exception e) {
System.out.println("CREATE TABLE `" + annotation.value()
+ "` (id INT PRIMARY KEY AUTO_INCREMENT ," + str + " );");
e.printStackTrace();
return "fail";
}
return "success";
}
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(createTableByAnnotations());
}
}
3、实体类
package com.peam.web.media;
import com.peam.web.media.annotation.FieldInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.TreeSet;
/**
* @author 施子安
* @version 1.0
* @date 2023/9/26 17:23
* @Description 下级资源节点信息列表
*/
@TableNameNew("xjlgqq_mediaInfo")
@TableName("xjlgqq_mediaInfo")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Ressource {
/** 资源id */
@FieldInfo(columnName = "id",columnType = "int",commit = "资源id")
private String id;
/** 资源名称 */
@FieldInfo(columnName = "text",columnType = "varchar(500)",commit = "资源名称")
private String text;
/** 设备简称 */
@FieldInfo(columnName = "devShortName",columnType = "varchar(500)",commit = "设备简称")
private String devShortName;
/** 资源打开方式 */
@FieldInfo(columnName = "openType",columnType = "int",commit = "资源打开方式")
private Integer openType;
/** 是否为分组*/
@FieldInfo(columnName = "isGroup",columnType = "int",commit = "是否为分组")
private Integer isGroup;
/** 纬度*/
@FieldInfo(columnName = "lat",columnType = "double",commit = "经度位置")
private BigDecimal lat;
/** 子节点数量*/
@FieldInfo(columnName = "childrenCount",columnType = "int",commit = "子节点数量")
private Integer childrenCount;
/** GIS侧标识设备的编码*/
@FieldInfo(columnName = "gisPeerCode",columnType = "varchar(255)",commit = "GIS侧标识设备的编码")
private String gisPeerCode;
/** 下级资源节点信息列表 */
@FieldInfo(columnName = "gisPeerCode",columnType = "longtext(500)",commit = "GIS侧标识设备的编码")
private TreeSet<RessourceVO> childNode;
}
4、pom.xml
<!--用于获取添加了某个注解的所有Class对象-->
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>