【问题标题】:Saving integer array using Spring Data JPA使用 Spring Data JPA 保存整数数组
【发布时间】:2018-11-15 07:44:25
【问题描述】:

我正在使用带有 hibernate 和 postgres 的 spring data jpa。我正在尝试将整数数组保存在一列中。我正在使用 vlad mihaceas 库将数组保存到 postgresql 中。实体如下:-

@Type(type = "int-array")
@Column(name = "location", columnDefinition = "integer[]")  
private Integer[] locations;    

对应的位置实体是

@Entity
@Table(name = "location_master")
public class Location implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(name = "location_name")
    private String locationName;
}

位置 ID 正在保存在数据库中。但我无法在百里香中显示。

<tr>
    <td>Selected Locations</td>
    <td>[[${office.locations[0].locationName}]]</td>
</tr>

出现以下错误:-

org.springframework.expression.spel.SpelEvaluationException: EL1008E: 在类型的对象上找不到属性或字段“locationName” 'java.lang.Integer' - 可能不公开或无效?

【问题讨论】:

  • 嗯,消息说明了一切。为什么您认为可以从 Integer 中获取 locationName?这是没有意义的。整数是整数。不是位置。如果您想要 Collection,则使用 Collection,并使其成为未知实体和 Location 实体之间的 OneToMany 关联。
  • @JB Nizet 我想将数据库中选定的位置 ID 保存为数组。我已经尝试过 List ,它给出了错误 Use of OneToMany or ManyToMany 针对未映射的类。由于 Hibernate 只映射原始类型,我使用的是 vlad mihalcea 的库
  • 这不是正确的数据库设计。使用外键、连接列、连接表和实体之间的关联。
  • @JBNizet 数据库设计不在我的控制范围内。我必须使用给我的东西。
  • 尝试使用@ElementCollection@CollectionTable注解

标签: java spring postgresql hibernate spring-data-jpa


【解决方案1】:

org.springframework.expression.spel.SpelEvaluationException: EL1008E: 在“java.lang.Integer”类型的对象上找不到属性或字段“locationName” - 可能不是公共的或无效的?

该错误与hibernate-types项目的int-array的使用无关。

错误消息是关于您用于设置 locationName 的 Spring 表达式语言 这是一个String 属性。

[[${office.locations[0].locationName}]]

locations 属性是 Integer[],但您将其视为 Location 数组。

你想要的是 @OneToMany List&lt;Location&gt; 代替:

@OneToMany(mappedBy="office", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Location> locations = new ArrayList<>();  

Location 中还有一个@ManyToOne 关联:

@ManyToOne(fetch = FetchType.LAZY)
private Office office;

查看this article,了解有关使用@OneToMany 关联的最佳方式的更多详细信息。

【讨论】:

  • 我知道这是一个 SpEL 错误,与休眠类型无关。也许我无法正确解释我的问题。 OneToMany List
  • 当然,他们会的。查看 GitHub 存储库中的休眠类型测试以获得证明。
  • 我不需要证明。在 jsonb 类型中,休眠类型对我来说已经可以正常工作了。我只是对如何在这些映射中使用 @Type type= int-array 注释感到困惑。您也没有在回答中提到它。
  • 我会提到它,异常消息会表明这一点。查看 this test case 了解如何使用 int-array 映射。只需将我的测试用例与您的测试用例进行比较,看看它们有何不同。
  • 是的,我看到了。你有一个整数数组,在我的例子中,它是一个对象列表。我无法弄清楚如何为此列表进行 int-array 映射
猜你喜欢
  • 2021-03-05
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 2019-09-30
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多