How to implement java to automatically create database tables under springBoot
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:
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!

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)
