Java通过反射注解自动创建mysql数据库表 - Go语言中文社区

Java通过反射注解自动创建mysql数据库表


Hibernate框架可以通过注解自动创建表,可以用java模仿Hibernate框架自己创建表和实现增删改查。
首先定义连接数据库的连接池:通过配置文件配置连接数据库。
jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/dvdstore?useSSL=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
jdbc.initialSize=5

datapool.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ResourceBundle;
import java.util.Stack;

public class DataPool {
	private static Stack<Connection> pool = new Stack<Connection>();
	static {
		try {
		//读取配置文件的信息
			ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
			String Driver = bundle.getString("jdbc.driver");
			String url = bundle.getString("jdbc.url");
			String user = bundle.getString("jdbc.username");
			String password = bundle.getString("jdbc.password");
			Integer size = Integer.valueOf(bundle.getString("jdbc.initialSize"));
			Class.forName(Driver);//// 另一种写法new com.mysql.jdbc.Driver();相当于driver写入内存
			for (int i = 0; i < size; i++) {
	Connection connection = DriverManager.getConnection(url, user, password);//创建连接
				pool.push(connection);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static Connection getConn() {
		return pool.pop();
	}
	public static void close(Connection connection) {
		pool.push(connection);
}

定义注解类:
Column.java

import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
	String value();//列名
	String type();//类型
	String isnull() default "null";
}

Table.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Table {
	String value();//表名
}

TablePrimaeyId.java

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(FIELD)
public @interface TablePrimaeyId {
	String value() default " primary key";//定义主键
	String increment() default "";//主键是否自动增长
}

定义创建数据库的类:dbinit.java

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.Dvd.Annotation.Column;
import com.Dvd.Annotation.Table;
import com.Dvd.Annotation.TablePrimaeyId;
import com.Dvd.poolSerivce.DataPool;
public class DBInit {
	public static void CreateTable(Object obj) {
		StringBuilder builder = new StringBuilder();// 用StringBuilder来拼接建表sql语句
		boolean present = obj.getClass().isAnnotationPresent(Table.class);// 利用反射判断类上面是否有注解
		if (!present) {
			return;
		}
		String name = obj.getClass().getAnnotation(Table.class).value();// 获取注解的值
		builder.append("create table if not exists " + name + "(");// 拼接sql语句
		Class<?> clz = obj.getClass();
		Field[] fields = clz.getDeclaredFields();// 获取传进来的对象的属性
		for (Field field : fields) {// 遍历属性
			Column column = field.getAnnotation(Column.class);// 获取属性注解名字
			TablePrimaeyId id = field.getAnnotation(TablePrimaeyId.class);// 获取主键的注解
			if (column != null) {
				builder.append(column.value() + " " + column.type() + " " + column.isnull());// 拼接数据库语句
				if (id != null) {
					builder.append(id.value() + " " + id.increment());
				}
				builder.append(",");
			}
		}
		// 因为该sql语句最后会多一个逗号,这里将其删除
		builder.deleteCharAt(builder.length() - 1);
		builder.append(")");
		// 打印sql语句
		// System.out.println(builder.toString());
		Connection conn = DataPool.getConn();
		if (conn != null) {
			try { // 执行对应的创建表操作
				PreparedStatement prepareStatement = conn.prepareStatement(builder.toString());
				prepareStatement.execute();
				prepareStatement.close();
				// 将连接放回线程池中
				DataPool.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

实体类:Dvd.java

package com.Dvd.po;

import com.Dvd.Annotation.Column;
import com.Dvd.Annotation.Table;
import com.Dvd.Annotation.TablePrimaeyId;

@Table("dvd")
public class Dvd {
	@TablePrimaeyId(increment = "auto_increment")
	//其实type也可以通过枚举类去实现
	@Column(value = "id", type = "int", isnull = "not null")
	private int id;
	@Column(value = "name", type = "varchar(50)")
	private String name;
	@Column(value = "price", type = "int")
	private int price;
	@Column(value = "author", type = "varchar(50)")
	private String author;

	public Dvd() {
	}

	public Dvd(String name, int price, String author) {
		super();
		this.name = name;
		this.price = price;
		this.author = author;
	}

	public Dvd(int id, String name, int price, String author) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.author = author;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	@Override
	public String toString() {
		return "Dvd [id=" + id + ", name=" + name + ", price=" + price + ", author=" + author + "]";
	}

}

测试 Test.java

public class Main {
	public static void main(String[] args) {
	DBInit.CreateTable(new Dvd());
	}
}

执行结果:
在这里插入图片描述在这里插入图片描述在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_41528317/article/details/83660679
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-27 22:55:48
  • 阅读 ( 984 )
  • 分类:数据库

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢