Home  >  Article  >  Java  >  How to implement java to automatically create database tables under springBoot

How to implement java to automatically create database tables under springBoot

WBOY
WBOYforward
2023-05-19 12:34:062922browse

SpringBoot environment startup project creates database table

Use environment

windows eclipse mysql navicat

Steps

1. Create SpringBoot project

2. Create a new database and configure the connection information

3. Write the initialization database table class

4. Run and view the results

1. Create a SpringBoot project

No more details on how to create a SpringBoot project, just create a SpringBoot project that can run.

2. Create a new database and configure the connection information

2.1 Create a new database

Open Navicat and create a new Mysql connection (connection information such as user name and password should be remembered, configure the connection information below (to use), create a new database after establishing the connection, and set the database name to "nfsj". This is set according to your own preferences. Just remember to modify the configuration information below.

2.2 Configure connection information

Find the following file in the project, open the file and add the configuration:

How to implement java to automatically create database tables under springBoot

Open the above file and add the following code :

# datasource
folivora.datasource.url=jdbc:mysql://localhost:3306/nfsj?useUnicode=true&characterEncoding=utf-8
folivora.datasource.username=root
folivora.datasource.password=123456
folivora.datasource.driver-class-name=com.mysql.jdbc.Driver

Note: The configuration information here is the same as the configuration information when you created the database.

3. Write an initialization database table class

Create a new package under the project directory src/main/java, register as you like, and create a new class under the package with the class name "InitSysAdminDivisions.java" (The class name can also be named by yourself).

InitSysAdminDivisions.java

package cn.idatatech.folivora.modules.sys.common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

//SpringBoot单元测试启动类注解
//@RunWith(SpringRunner.class)
//@SpringBootTest
//@Component
@Repository  //继承自@Component,作用于持久层
/**
 * 如果配置文件没有在默认目录下,使用注解@PropertySource获取,下面演示的是在多配置文件中获取相同属性名的值,以后置为准
 * 单配置文件只要一个路径参数就可以
 */
//@PropertySource({"classpath:application.properties","classpath:config/config.properties"})  
public class InitSysAdminDivisions {

	@Value(value = "${folivora.datasource.driver-class-name}")
	private String driver;   
	
	@Value(value = "${folivora.datasource.url}")
	private String url;   
	
	@Value(value = "${folivora.datasource.username}")
	private String userName;
	
	@Value(value = "${folivora.datasource.password}")
	private String password;
	
	@PostConstruct
	public void init() throws SQLException, ClassNotFoundException{
		//连接数据库
		Class.forName(driver);
		//测试url中是否包含useSSL字段,没有则添加设该字段且禁用
		if( url.indexOf("?") == -1 ){
			url = url + "?useSSL=false" ;
		}
		else if( url.indexOf("useSSL=false") == -1 || url.indexOf("useSSL=true") == -1 )
		{
			url = url + "&useSSL=false";
		}
		Connection conn = DriverManager.getConnection(url, userName, password);
		Statement stat = conn.createStatement();
		//获取数据库表名
		ResultSet rs = conn.getMetaData().getTables(null, null, "sys_admin_divisions", null);
		
		// 判断表是否存在,如果存在则什么都不做,否则创建表
		if( rs.next() ){
			return;
		}
		else{
			// 先判断是否纯在表名,有则先删除表在创建表
//			stat.executeUpdate("DROP TABLE IF EXISTS sys_admin_divisions;CREATE TABLE sys_admin_divisions("
			//创建行政区划表
			stat.executeUpdate("CREATE TABLE sys_admin_divisions("
					+ "ID varchar(32) NOT NULL COMMENT "行政区划ID(行政区划代码)这里不使用32位的UUID,使用全数字的行政区域代码作为ID(如:440000)","
					+ "TYPE varchar(50) DEFAULT NULL COMMENT "类型(1省级 2市级 3区县)","
					+ "CODE varchar(50) DEFAULT NULL COMMENT "字母代码","
					+ "NAME varchar(100) DEFAULT NULL COMMENT "名称","
					+ "PINYIN varchar(100) DEFAULT NULL COMMENT "拼音","
					+ "PARENT_ID varchar(32) DEFAULT NULL COMMENT "上级行政区划数字代码","
					+ "IS_DISPLAY int(1) DEFAULT NULL COMMENT "是否显示( 0:否 1:是 )","
					+ "SORT bigint(20) DEFAULT NULL COMMENT "排序标识","
					+ "DEL_FLAG int(1) DEFAULT NULL COMMENT "删除标识(0:正常 1:已删除)","
					+ "PRIMARY KEY (ID)"
					+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT="行政区划 (省市区)";"
					);
		}
		// 释放资源
		stat.close();
        conn.close();
	}
}

Note: The above table creation logic is to first determine whether the table to be created exists in the database, and if so, return without performing any operation. If the table to be created does not exist in the database, a new table is created. The specific logic can be defined according to your own needs.

Remove the judgment operation to determine whether the table exists in the database. You can also use the commented out "If the table exists, delete the table first and then create the table (this will delete the data in the original table)."

4. Run to view the results

Find the Application.java class in the project, run the class, and after the operation is completed, open navicate to view your own database and find that a database has been created. The table "sys_admin_divisions" and the related fields in the table.

The above is the detailed content of How to implement java to automatically create database tables under springBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete