gpt4 book ai didi

jakarta-ee - 使用 JPA Play Framework : Solution for storing a Map, 键值

转载 作者:行者123 更新时间:2023-12-02 02:54:17 25 4
gpt4 key购买 nike

我花了将近一周的时间来研究如何在 Play 中使用 JPA 存储 HashMap。所有其他属性都被存储,只有 HashMap 有零个元素(为空)。

public class ImageModel extends Model {

@Id
private String id;
private String url;

@ElementCollection(targetClass = java.lang.String.class)
@MapKeyClass(java.lang.String.class)
private Map<String,String> tags = new HashMap<>();

// the method for adding keys and values to the HashMap
public void add(String key, String value){
tags.put(key,value);
this.save();
}

}

我还尝试用以下方式进行注释:

@ElementCollection(fetch=FetchType.LAZY)

所以,我现在唯一的猜测是我没有配置好Play。 (我必须说,我使用的是Play2,除了删除数据库设置前面的“#”(注释标记)之外,没有进行任何配置。

On Play 文档显示:“Play 2.0 中没有内置 JPA 实现”。可能是这样吗?

更新:我做了一些研究,并表示这可能是因为我使用的是 Play - H2 的默认数据库。我尝试使用 MySQL - video how to do it ,但同样它只保存 id 和 url。我查看了 MySQL 数据库和表,其中类名只有 2 个属性(id 和 url),没有我的 HashMap 的踪迹。

更新2:添加了打印屏幕 - with database query.

Update3:Play 中的示例“computer-database-jpa”工作正常,因此 JPA 应该没问题,但该示例没有使用 Map (HashMap)。我什至用 EclipseLink 更改了 hibernate,但仍然无法工作。 :((尽管所有基本类型属性都在数据库中)

最佳答案

以下是我如何使用您的模型实现 HashMap。

@Entity
public class ImageModel extends Model {
//All your fields, etc.

@ManyToMany(mappedBy = "imagesWithTag")
@MapKey(name = "name")
public Map<String,Tag> tags = new HashMap<String,Tag>();
}

@Entity
public class Tag extends Model {
// All your fields, etc.

public String name;
public String value;

@ManyToMany
public List<ImageModel> imagesWithTag = new ArrayList<ImageModel>();
}

我决定采纳 Eric 的建议,为 Tag 创建一个完整的模型,以便轻松进行查询,但有时能够使用 Map 的功能会有很大帮助。这也适用于 EnumMap。

public void addTag(String tagName, String value) {
Tag tag = Tag.finderTag.where().eq("name", tagName).eq("value", value).findUnique();
if(tag == null) {
tag = Tag.newTag(tagName, value);
}
this.tags.put(tag.name, tag);
this.saveManyToManyAssociations("tags");
}

public static List<ImageModel> getImagesWithTag(String tagName, String tagValue) {

Tag tag = finderTag.where().eq("name", tagName).eq("value", tagValue).findUnique();

List<ImageModel> images = new ArrayList<ImageModel>();
for(ImageModel model : tag.imagesWithTag) {
images.add(model);
}
return images;
}

我几乎没有看到任何有关在 Play 框架模型中使用 map 的信息,因此我决定创建一个小型示例项目 (Play 2.1.1) 来尝试并进一步演示 map 的使用。

https://github.com/Raymond26/play-framework-demos/tree/master/PlayMap

关于jakarta-ee - 使用 JPA Play Framework : Solution for storing a Map, 键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16818155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com