社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
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());
}
}
执行结果:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!