import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
public class DatabaseSyncPlugin extends JavaPlugin {
private SessionFactory sessionFactory;
private List<MyData> data = new ArrayList<>();
private boolean fetching = false;
@Override
public void onEnable() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(MyData.class);
sessionFactory = configuration.buildSessionFactory();
new BukkitRunnable() {
@Override
public void run() {
if (!fetching) {
fetchData();
}
}
}.runTaskTimer(this, 0L, 200L);
}
private void fetchData() {
fetching = true;
CompletableFuture.runAsync(() -> {
try (Session session = sessionFactory.openSession()) {
List<MyData> fetchedData = session.createQuery("from MyData", MyData.class).list();
new BukkitRunnable() {
@Override
public void run() {
data.clear();
data.addAll(fetchedData);
fetching = false;
}
}.runTask(this);
} catch (Exception e) {
getLogger().severe("Error fetching data: " + e.getMessage());
e.printStackTrace();
new BukkitRunnable() {
@Override
public void run() {
fetching = false;
}
}.runTask(this);
}
});
}
public List<MyData> getData() {
return new ArrayList<>(data);
}
@Override
public void onDisable() {
if (sessionFactory != null) {
sessionFactory.close();
}
}
@Entity
public static class MyData {
@Id
private int id;
@Column
private String name;
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; }
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/your_database?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">your_username</property>
<property name="connection.password">your_password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.group.id</groupId>
<artifactId>DatabaseSyncPlugin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.18.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.10.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.18.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>org.hibernate</pattern>
<shadedPattern>shadow.org.hibernate</shadedPattern>
</relocation>
<relocation>
<pattern>org.dom4j</pattern>
<shadedPattern>shadow.org.dom4j</shadedPattern>
</relocation>
<relocation>
<pattern>antlr</pattern>
<shadedPattern>shadow.antlr</shadedPattern>
</relocation>
<relocation>
<pattern>javax.persistence</pattern>
<shadedPattern>shadow.javax.persistence</shadedPattern>
</relocation>
<relocation>
<pattern>javax.transaction</pattern>
<shadedPattern>shadow.javax.transaction</shadedPattern>
</relocation>
<relocation>
<pattern>net.bytebuddy</pattern>
<shadedPattern>shadow.net.bytebuddy</shadedPattern>
</relocation>
<relocation>
<pattern>com.mysql</pattern>
<shadedPattern>shadow.com.mysql</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
plugin.yml:
name: DatabaseSyncPlugin
version: 1.0
main: DatabaseSyncPlugin
api-version: 1.18
Explanation:
- Dependencies: The
pom.xml includes the necessary dependencies for Spigot API, Paper API (if you are using Paper), Hibernate, and MySQL Connector/J. Crucially, it uses maven-shade-plugin to shade Hibernate and its dependencies. This prevents conflicts with potentially different versions of these libraries that other plugins might be using.
- Hibernate Configuration: The
hibernate.cfg.xml file configures Hibernate to connect to your MySQL database. Replace your_database, your_username, and your_password with your actual database credentials. The hbm2ddl.auto property is set to update, which automatically updates the database schema based on the entity classes.
- Plugin Class:
onEnable(): Initializes the Hibernate SessionFactory and starts the data synchronization task. The task runs every 10 seconds (200 ticks).
fetchData(): This method is the core of the synchronization logic.
- It sets the
fetching flag to true to prevent overlapping tasks.
- It uses
CompletableFuture.runAsync() to perform the database query asynchronously, preventing server lag.
- Inside the asynchronous task, it opens a Hibernate
Session and queries the database for all MyData entities.
- It then uses
BukkitRunnable.runTask() to schedule a task on the main thread to update the data list with the fetched data. This ensures that any data access from the main thread is thread-safe.
- It sets the
fetching flag back to false after the data is updated.
- Includes a try-catch to properly set
fetching to false in case of errors.
getData(): Provides a method to safely access a copy of the synchronized data from the main thread. It returns a new ArrayList to avoid concurrent modification issues.
onDisable(): Closes the Hibernate SessionFactory when the plugin is disabled.
MyData Entity: Defines a simple entity class representing the data you want to synchronize. It uses JPA annotations (@Entity, @Id, @Column) to map the class to a database table.
How to Use:
- Configure
hibernate.cfg.xml: Replace the placeholder values with your actual database credentials.
- Database Setup: Create the
your_database database in MySQL if it doesn't exist. Hibernate will automatically create the MyData table based on the entity class.
- Build the Plugin: Use Maven to build the plugin:
mvn clean package. This will create a JAR file in the target directory.
- Install the Plugin: Copy the JAR file to your Minecraft server's
plugins folder.
- Start the Server: Start your Minecraft server. The plugin will automatically load and begin synchronizing data from the database every 10 seconds.
- Access the Data: Use the
getData() method to access the synchronized data from other parts of your plugin. For example:
List<DatabaseSyncPlugin.MyData> currentData = plugin.getData();
for (DatabaseSyncPlugin.MyData dataItem : currentData) {
// Do something with dataItem.getId() and dataItem.getName()
}
Important Considerations:
- Database Connection: Make sure your MySQL server is running and accessible from your Minecraft server.
- Error Handling: Add more robust error handling and logging to your plugin to catch and report any issues that may occur during database synchronization.
- Data Volume: For large datasets, consider using pagination or other techniques to efficiently load data from the database. Loading the entire dataset into memory every 10 seconds might become a performance bottleneck.
- Transaction Management: If you need to perform complex database operations involving multiple entities, use Hibernate's transaction management features to ensure data consistency.
- Data Types: Ensure that the data types in your entity classes match the data types in your database table.
- Asynchronous Operations: Be very careful when working with asynchronous operations in Bukkit plugins. Always ensure that any Bukkit API calls are made on the main thread.
- Testing: Thoroughly test your plugin to ensure that it is working correctly and that it does not cause any performance issues on your server.
- Security: Never hardcode database credentials directly in your code. Use a configuration file or other secure method to store your credentials.
This improved version addresses the potential issues of overlapping tasks, main thread access, error handling, and dependency conflicts, providing a more robust and reliable solution for synchronizing data from a database to your Minecraft plugin.