GithubHelp home page GithubHelp logo

simpleorm's Introduction

SimpleORM

A Bukkit plugin provides a central ORM Manager. It have no reload issue from Bukkit's build-in ORM support.

Usage

Put it into your server's plugin folder, and start your server, or package source into your own plugin(not recommend). This is a sample project xKit.

Developer

If you want to use this library in your own plugin. code your main class like this. See Ebean ORM

public class MyPlugin extends JavaPlugin {
    
    @Override
    public void onEnable() {
        /*
         * If you dont whan to use manager object, follow this
         * code. NOT RECOMMEND.
         *
         * EbeanHandler handler = new EbeanHandler();
         * handler.setDriver("com.mysql.jdbc.Driver");
         * handler.setUrl("jdbc:mysql://localhost:3306/database");
         * handler.setUserName("userName");
         * handler.setPassword("password");
         *
         * Use manager object will gen and read config field automatic.
         * and will store handler into a map, your can get it even
         * your plugin reload.
         *
         */
        // EbeanManager manager = EbeanManager.DEFAULT;
        EbeanManager manager = getServer().getServicesManager()
                .getRegistration(EbeanManager.class)
                .getProvider();
        EbeanHandler handler = manager.getHandler(this);

        if (!handler.isInitialize()) {
            handler.define(MyClass.class);
            handler.define(MyOther.class);
            try {
                handler.initialize();
            } catch(Exception e) {
                // Do what you want to do.
            }
        }
        // This function will inject into Bukkit's build-in 
        // ORM support.
        handler.reflect();
        // This function will try to create not exists tables.
        handler.install();
        // Injected build-in method. Return initialized 
        // Ebean server.
        EbeanServer server = this.getDatabase();
        // EbeanServer server = handler.getServer();
        // ...
    }
    
    public void function() {
        MyClass my = getDatabase.find(MyClass.class)
                                .where()
                                .eq("name", "zmy")
                                .findUnique();
        System.out.print(my.getName());
        // ...
    }
}

Code your entity class like this. See More Example.

@Entity
@Table(name = "o_table")
public class MyClass {
    
    @Id
    private int id;
    
    @Column
    private String name;
    
    // Put getter and setter.
}

Configure field will create automatic in your plguin's default config file. Like this.

dataSource:
  driver: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost/database
  userName: username
  password: password

Attention

  • A @ManyToOne field is lazy load!
  • A @ManyToOne field is not support on sqlite platform!

Redis wrapper

import com.mengcraft.simpleorm.ORM
import com.mengcraft.simpleorm.RedisWrapper

RedisWrapper redisWrapper = ORM.globalRedisWrapper();
redisWrapper.open(redis -> {
    redis.set("my_key", "my_value");
    // more codes here
});

redisWrapper.subscribe("my_channel", message -> {
    Foo foo = Foo.decode(message);
    // codes here
});

redisWrapper.publish("my_channel", "my_message");

If you want to enable sentinel mode, make sure master_name is a non-empty string, or make sure it is null. An example is shown below.

redis:
  master_name: i_am_master
  url: redis://host1:26379,host2:26379,host3:26379
  max_conn: 20

Serializer

Simple serializer and deserializer based on Gson with ConfigurationSerializable, ScriptObjectMirror and JSR310 supported.

import com.google.common.base.Preconditions
import com.mengcraft.simpleorm.ORM
import org.bukkit.Bukkit
import org.bukkit.Location

Location loc = new Location(Bukkit.getWorld("world"), 0, 0, 0)

Map<String, Object> map = ORM.serialize(loc)
Location loc2 = ORM.deserialize(Location.class, map)

Preconditions.checkState(Objects.equals(loc, loc2))

Async executors

Schedule async task to specific async pool or primary thread.

import com.mengcraft.simpleorm.ORM;

import java.util.function.Supplier;

ORM.enqueue("pool_name", () -> "any_async_task")
        .thenComposeAsync(obj -> {
            // Codes here
        })

ORM.sync(() -> "any_sync_task")
        .thenAccept(s -> {
            // Codes here
        })

Distributed L2 caches

import com.mengcraft.simpleorm.ORM
import com.mengcraft.simpleorm.redis.SimpleCache

def static customCalculator(String key) {
    "hello, " + key
}

def cache = ORM.globalRedisWrapper().openCache(SimpleCache.Options.builder()
        .name("sample")
        .calculator(this::customCalculator)
        .clustered(true)
        .expire(300)
        .expire2(3600)
        .build())

cache.get("key")
        .thenAccept({
            cache.set("key", it)
        })

cache.expire("key")

if (cache.isCached("key2")) {
    cache.expire2("key2")
}

simpleorm's People

Contributors

caoli5288 avatar

Stargazers

 avatar  avatar Summer Samantha avatar  avatar Nine9 avatar Koyorice_ avatar 秋 雨落 avatar VanishTime733 avatar KID avatar Lucas avatar  avatar Zhang ZhiYuan  avatar Baran OZCAN avatar  avatar Robin23 avatar Ree avatar paihuai avatar Titiwut Muktikanantakun avatar  avatar

Watchers

Lucas avatar  avatar Zhang ZhiYuan  avatar  avatar Baran OZCAN avatar

simpleorm's Issues

梦梦,有个关于Redis的问题

梦梦你好,我在使用redisWrapper的遇到一个的问题,就是我插件能顺利编译,但是在运行的时候出现了java.lang.NoSuchMethodError.
下面是我的代码

    public void addWorld(String worldName) {
        redisWrapper.open(redis -> {
            String s = redis.clientInfo();
            Log.console(s);
            redis.sadd(RedisKeyEnums.getFormatKey(RedisKeyEnums.BC_SERVER_WORLDS, this.serverName), worldName);
        });
    }

下面是我控制台的输出

[00:19:46] [Server thread/INFO]: [SumBcSuite] id=35 addr=127.0.0.1:55603 laddr=127.0.0.1:6379 fd=7 name= age=16 idle=0 flags=N db=0 sub=0 psub=0 ssub=0 multi=-1 qbuf=26 qbuf-free=20448 argv-mem=10 multi-mem=0 rbs=1024 rbp=4 obl=0 oll=0 omem=0 tot-mem=22298 events=r cmd=client|info user=default redir=-1 resp=2
[00:19:46] [Server thread/WARN]: [SumBcSuite] Task #64 for SumBcSuite v1.0.0 generated an exception
java.lang.NoSuchMethodError: redis.clients.jedis.Jedis.sadd(Ljava/lang/String;[Ljava/lang/String;)J
        at net.sumcraft.spigot.managers.BcServerInfoMgr.lambda$addWorld$1(BcServerInfoMgr.java:131) ~[?:?]
        at com.mengcraft.simpleorm.RedisWrapper.open(RedisWrapper.java:112) ~[?:?]
        at net.sumcraft.spigot.managers.BcServerInfoMgr.addWorld(BcServerInfoMgr.java:128) ~[?:?]
        at net.sumcraft.spigot.managers.BcServerInfoMgr.loadWorlds(BcServerInfoMgr.java:168) ~[?:?]
        at net.sumcraft.spigot.listeners.ServerInfoListener$1.run(ServerInfoListener.java:78) ~[?:?]
        at org.bukkit.craftbukkit.v1_12_R1.scheduler.CraftTask.run(CraftTask.java:76) ~[CraftTask.class:git-CatServer-1.12.2-8d58cdb8]
        at org.bukkit.craftbukkit.v1_12_R1.scheduler.CraftScheduler.mainThreadHeartbeat(CraftScheduler.java:421) [CraftScheduler.class:git-CatServer-1.12.2-8d58cdb8]
        at net.minecraft.server.MinecraftServer.func_71190_q(MinecraftServer.java:900) [MinecraftServer.class:?]
        at net.minecraft.server.dedicated.DedicatedServer.func_71190_q(DedicatedServer.java:475) [nz.class:?]
        at net.minecraft.server.MinecraftServer.func_71217_p(MinecraftServer.java:834) [MinecraftServer.class:?]
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:693) [MinecraftServer.class:?]
        at java.lang.Thread.run(Thread.java:748) [?:1.8.0_271]

下面是SimpleORM加载的控制台输出

[00:19:08] [Server thread/INFO]: [SimpleORM] Loading SimpleORM v1.9.0-SNAPSHOT
[00:19:08] [Server thread/INFO]: Load MavenLibs(javax/persistence/persistence-api/1.0)
[00:19:08] [Server thread/INFO]: Load MavenLibs(org/avaje/ebean/2.8.1)
[00:19:08] [Server thread/INFO]: Load MavenLibs(org/slf4j/slf4j-api/1.7.30)
[00:19:08] [Server thread/INFO]: Load MavenLibs(com/zaxxer/HikariCP/4.0.3)
[00:19:08] [Server thread/INFO]: Load MavenLibs(org/apache/commons/commons-pool2/2.11.1)
[00:19:08] [Server thread/INFO]: Load MavenLibs(redis/clients/jedis/3.8.0)
[00:19:08] [Server thread/INFO]: [SimpleORM] ORM lib load okay!

在服务器启动的插件加载的时候redis也能ping,然后返回pong,
这是完整日志,https://pastebin.com/WaDJUamf

java.lang.ClassNotFoundException: io.ebean.bean.EntityBean


1. package Main;
2. 
3. 
4. import org.bukkit.plugin.java.JavaPlugin;
5. 
6. import com.avaje.ebean.EbeanServer;
7. import com.mengcraft.simpleorm.EbeanHandler;
8. import com.mengcraft.simpleorm.EbeanManager;
9. 
10. 
11. public class Core extends JavaPlugin{
12. 
13. 	EbeanServer server;
14. 	
15. 	@SuppressWarnings({ "deprecation" })
16. 	@Override
17. 	public void onEnable()
18. 	{
19. 		EbeanManager manager = getServer().getServicesManager()
20. 				.getRegistration(EbeanManager.class)
21. 				.getProvider();
22. 		EbeanHandler handler = manager.getHandler(this);
23. 		
24. 		if (!handler.isInitialized()) {
25. 			handler.define(Guild.class);
26. 			try {
27. 				handler.initialize();
28. 			} catch(Exception e) {
29. 			}
30. 		}
31. 		handler.reflect();
32. 		handler.install();
33. 		server = handler.getServer();
34. 		
35. 		
36. 		testGuild();
37. 		
38. 	}
39. 	
40. 	
41. 	public void testGuild() 
42. 	{
43. 		Guild g = new Guild();
44. 		server.save(g);
45. 	}
46. }
47. 

1. package Main;
2. 
3. import javax.persistence.Entity;
4. import javax.persistence.Id;
5. import javax.persistence.Table;
6. 
7. @Entity
8. @Table(name = "Guilds")
9. public class Guild {
10. 
11. @Id
12. private int guildId;
13. 
14. private String guildName;
15. 
16. /**
17. * @return the guildId
18. */
19. public int getGuildId() {
20. return guildId;
21. }
22. 
23. /**
24. * @param guildId the guildId to set
25. */
26. public void setGuildId(int guildId) {
27. this.guildId = guildId;
28. }
29. 
30. /**
31. * @return the guildName
32. */
33. public String getGuildName() {
34. return guildName;
35. }
36. 
37. /**
38. * @param guildName the guildName to set
39. */
40. public void setGuildName(String guildName) {
41. this.guildName = guildName;
42. }
43. 
44. 
45. }
46. 

21:24:44 [ERROR] Error occurred while enabling Guilds v0.1 (Is it up to date?)
21:24:44 java.lang.NoClassDefFoundError: io/ebean/bean/EntityBean
21:24:44 at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.8.0_144]
21:24:44 at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[?:1.8.0_144]
21:24:44 at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[?:1.8.0_144]
21:24:44 at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:131) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.plugin.java.JavaPluginLoader.getClassByName(JavaPluginLoader.java:202) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:92) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:81) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_144]
21:24:44 at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_144]
21:24:44 at Main.Core.onEnable(Core.java:25) ~[?:?]
21:24:44 at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:263) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:352) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:417) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.craftbukkit.v1_14_R1.CraftServer.enablePlugin(CraftServer.java:461) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.craftbukkit.v1_14_R1.CraftServer.enablePlugins(CraftServer.java:375) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at net.minecraft.server.v1_14_R1.MinecraftServer.a(MinecraftServer.java:439) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at net.minecraft.server.v1_14_R1.DedicatedServer.init(DedicatedServer.java:258) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at net.minecraft.server.v1_14_R1.MinecraftServer.run(MinecraftServer.java:764) [spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at java.lang.Thread.run(Thread.java:748) [?:1.8.0_144]
21:24:44 Caused by: java.lang.ClassNotFoundException: io.ebean.bean.EntityBean
21:24:44 at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_144]
21:24:44 at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:135) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:81) ~[spigot-1.14.3.jar:git-Spigot-5e4e7f3-2349feb]
21:24:44 at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_144]
21:24:44 at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_144]

Array out of bound exception

When I try to use stream in an entity I get an array out of bound exception. Probably the old version of ebean causes this.

mavenlib加载某些库时报错

mavenlib在加载com.fasterxml.jackson.core:jackson-databind:2.11.1的时候会在加载jackson-annotations的时候版本号读为"null",然后报错

梦梦,有个BUG...

目前遇到两个BUG,已经找到原因并解决。但没怎么用github,还不知道怎么提交给你,所以这里提出来。。。

第一个问题:MavenLibrary类的getSublist在解析pom文件时,如果第一个节点为注释节点,会直接跳过该pom文件,并不会找到依赖库。
第55行后改为,当找到project节点后再往下走。
Node pom = XMLHelper.getDocumentBy(xml).getFirstChild();
while (!pom.getNodeName().equals("project")){
pom=pom.getNextSibling();
}

第二个问题是:
在验证MD5时,有一些pom文件是会出现 'md5 xx xxxxx'这样的情况。你直接读第一行然后进行比较会出现问题。
应该改为读一个空格之前的字符串。
代码位置也在上面那个类的isLoadable方法。return改为
return Files.newBufferedReader(check.toPath()).readLine().split(" ")[0].equals(MD5.digest())

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.