json怎么读取数据库_如何:使用Json插入数据库并从中读取
json怎么讀取數據庫
在本文中,我們將為Speedment創建一個插件,該插件使用Gson生成序列化和反序列化邏輯,從而使其在數據庫實體和JSON字符串之間進行映射非常容易。 這將有助于展示Speedment代碼生成的可擴展性,同時探索Gson庫的一些很酷的功能。
Speedment是用于Java的代碼生成工具,可連接到數據庫并用作生成項目的實體和管理器文件的參考。 該工具是非常模塊化的,允許您編寫自己的插件來修改結果代碼的外觀。 幾個人在Gitter聊天中提到的一件事是,Speedment實體被聲明為抽象,從而阻止了它們自動反序列化。 在本文中,我們將研究如何通過自動為數據庫中的每個表生成一個自定義TypeAdapter來使用Gson反序列化Speedment實體。 這不僅可以在使用數據庫內容的JSON表示形式時為我們提供更好的性能,而且還可以作為有關如何擴展代碼生成器來解決問題的一般示例。
步驟1:創建插件項目
在上一篇文章中,我詳細介紹了如何為Speedment創建新的插件,所以這里是簡短的版本。 創建一個新的maven項目,并將Speedment和Gson設置為依賴項。
pom.xml
<name>Speedment Gson Plugin</name> <description>A plugin for Speedment that generates Gson Type Adapters for every table in the database. </description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><speedment.version>2.3.7</speedment.version> </properties><dependencies><dependency><groupId>com.speedment</groupId><artifactId>speedment</artifactId><version>${speedment.version}</version></dependency><dependency><artifactId>gson</artifactId><groupId>com.google.code.gson</groupId><version>2.6.2</version></dependency> </dependencies>步驟2:為類型適配器創建翻譯器類
接下來,我們需要創建將為我們生成新類型適配器的轉換器。 翻譯器是一個類,它描述生成的文件將具有的名稱,路徑和內容。 為此,它提供了許多便利的方法來簡化代碼生成。 轉換器的基本結構如下所示。
GeneratedTypeAdapterTranslator.java
... public GeneratedTypeAdapterTranslator(Speedment speedment, Generator gen, Table table) {super(speedment, gen, table, Class::of); }@Override protected Class makeCodeGenModel(File file) {return newBuilder(file, getClassOrInterfaceName()).forEveryTable((clazz, table) -> {// Code generation goes here}).build(); }@Override protected String getClassOrInterfaceName() {return "Generated" + getSupport().typeName() + "TypeAdapter"; }@Override protected String getJavadocRepresentText() {return "A Gson Type Adapter"; }@Override public boolean isInGeneratedPackage() {return true; } ...每個轉換器都是使用可使用newBuilder()方法調用的構建器模式構建的。 稍后當我們要修改現有翻譯器時,這一點變得很重要。 實際的代碼在構建器的forEveryTable()方法內部生成。 這是一個回調,將針對感興趣范圍中遇到的每個表執行該回調。 在這種情況下,翻譯器一次只能在一個表上執行,因此回調將只執行一次。
有關GeneratedTypeAdapterTranslator-class的完整資源,請轉到此github頁面 。
步驟3:創建用于修改管理器界面的裝飾器
但是,僅生成一堆TypeAdapter是不夠的。 我們希望將新代碼集成到已經存在的管理器中。 為此,我們需要定義一個裝飾器,該裝飾器將在執行默認邏輯后應用于所有生成的管理器。
GeneratedManagerDecorator.java
public final class GeneratedManagerDecorator implements TranslatorDecorator<Table, Interface> {@Overridepublic void apply(JavaClassTranslator<Table, Interface> translator) {translator.onMake((file, builder) -> {builder.forEveryTable(Translator.Phase.POST_MAKE, (clazz, table) -> {clazz.add(Method.of("fromJson", translator.getSupport().entityType()).add(Field.of("json", STRING)));});});} }裝飾器與翻譯器類似,不同之處在于它僅定義應對現有文件進行的更改。 每個裝飾器都在特定階段執行。 在本例中,我們要在生成默認代碼后執行,因此我們選擇POST_MAKE。 我們要添加的邏輯很簡單。 在接口中,我們需要fromJson(String)的其他方法。 我們不需要定義toJson,因為每個Speedment管理器已經從繼承的接口獲得了toJson。
步驟4:創建用于修改Manager實現的裝飾器
管理器實現的修改有些棘手。 我們需要為其添加Gson實例作為成員變量,剛剛添加的新接口方法的實現,使用Gson而不是內置序列化器的toJson方法的替代,并且我們需要修改管理器構造函數使用我們的新TypeAdapter實例化Gson。
GeneratedManagerImplDecorator.java
public final class GeneratedManagerImplDecorator implements TranslatorDecorator<Table, Class> {@Overridepublic void apply(JavaClassTranslator<Table, Class> translator) {final String entityName = translator.getSupport().entityName();final String typeAdapterName = "Generated" + entityName + "TypeAdapter";final String absoluteTypeAdapterName =translator.getSupport().basePackageName() + ".generated." + typeAdapterName;Final Type entityType = translator.getSupport().entityType();translator.onMake((file, builder) -> {builder.forEveryTable(Translator.Phase.POST_MAKE, (clazz, table) -> {// Make sure GsonBuilder and the generated type adapter // are imported.file.add(Import.of(Type.of(GsonBuilder.class)));file.add(Import.of(Type.of(absoluteTypeAdapterName)));// Add a Gson instance as a private memberclazz.add(Field.of("gson", Type.of(Gson.class)).private_().final_());// Find the constructor and define gson in itclazz.getConstructors().forEach(constr -> {constr.add("this.gson = new GsonBuilder()",indent(".setDateFormat(\"" + DATE_FORMAT + "\")"),indent(".registerTypeAdapter(" + entityName + ".class, new " + typeAdapterName + "(this))"),indent(".create();"));});// Override the toJson()-methodclazz.add(Method.of("toJson", STRING).public_().add(OVERRIDE).add(Field.of("entity", entityType)).add("return gson.toJson(entity, " + entityName + ".class);"));// Override the fromJson()-methodclazz.add(Method.of("fromJson", entityType).public_().add(OVERRIDE).add(Field.of("json", STRING)).add("return gson.fromJson(json, " + entityName + ".class);"));});});} }步驟5:將所有新類安裝到平臺中
創建所有新類后,我們需要創建一個組件和一個組件安裝程序,可以從要使用該插件的任何項目中引用該組件和組件安裝程序。
GsonComponent.java
public final class GsonComponent extends AbstractComponent {public GsonComponent(Speedment speedment) {super(speedment);}@Overridepublic void onResolve() {final CodeGenerationComponent code = getSpeedment().getCodeGenerationComponent();code.put(Table.class, GeneratedTypeAdapterTranslator.KEY, GeneratedTypeAdapterTranslator::new);code.add(Table.class, StandardTranslatorKey.GENERATED_MANAGER, new GeneratedManagerDecorator());code.add(Table.class,StandardTranslatorKey.GENERATED_MANAGER_IMPL, new GeneratedManagerImplDecorator());}@Overridepublic Class<GsonComponent> getComponentClass() {return GsonComponent.class;}@Overridepublic Software asSoftware() {return AbstractSoftware.with("Gson Plugin", "1.0", APACHE_2);}@Overridepublic Component defaultCopy(Speedment speedment) {return new GsonComponent(speedment);} }GsonComponentInstaller.java
public final class GsonComponentInstaller implements ComponentConstructor<GsonComponent> {@Overridepublic GsonComponent create(Speedment speedment) {return new GsonComponent(speedment);} }用法
當我們要在項目中使用我們的新插件時,我們只需將其作為依賴項添加到pom的依賴項部分中,并作為speedment maven插件下的依賴項進行添加。 然后,我們向插件添加配置標簽,如下所示:
<plugin><groupId>com.speedment</groupId><artifactId>speedment-maven-plugin</artifactId><version>${speedment.version}</version><dependencies><dependency><groupId>com.speedment.plugins</groupId><artifactId>gson</artifactId><version>1.0.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.39</version></dependency></dependencies><configuration><components><component implementation="com.speedment.plugins.gson.GsonComponentInstaller" /></components></configuration> </plugin>然后,我們可以重新生成代碼,然后應該可以訪問新的序列化和反序列化邏輯。
final String pippi = "{" + "\"id\":1," +"\"bookId\":-8043771945249889258," +"\"borrowedStatus\":\"AVAILABLE\"," + "\"title\":\"Pippi L?ngstr?m\"," + "\"authors\":\"Astrid Lindgren\"," + "\"published\":\"1945-11-26\"," + "\"summary\":\"A story about the world's strongest little girl.\"" + "}";books.fromJson(pippi).persist();摘要
在本文中,我們創建了一個新的Speedment插件,該插件為數據庫中的每個表生成了Gson TypeAdapters,并將這些適配器與現有的manager集成在一起。 如果您想要更多有關如何使用Speedment代碼生成器來提高生產力的示例, 請查看GitHub頁面 !
直到下一次!
翻譯自: https://www.javacodegeeks.com/2016/10/insert-read-database-using-json.html
json怎么讀取數據庫
總結
以上是生活随笔為你收集整理的json怎么读取数据库_如何:使用Json插入数据库并从中读取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 教你一招设置密码电脑如何让设置密码
- 下一篇: jhipster_JHipster入门,