【问题标题】:ResultSet containing EnumSet produces Table doesn't exist包含 EnumSet 的 ResultSet 生成 Table 不存在
【发布时间】:2021-06-12 13:51:11
【问题描述】:

我有一个像这样的枚举

enum class AmenitiesEnum {
POOL,
PETS_ALLOWED
// shortened list, for demo purpose only
}

这个 Enum 被包含在一个类中,然后在 MySQL 数据库中持久化。

@Entity
@Table(name = "hotels")
class Hotel (

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
override val id: Int? = null,

override val name: String,

@Enumerated(EnumType.STRING)
val rating: RatingsEnum?,

@OneToMany(mappedBy = "hotel", cascade = [CascadeType.ALL])
val rooms : List<Room> = ArrayList<Room>(),

// below code seems to be the issue

@ElementCollection
@Enumerated(EnumType.STRING)
val amenities: Set<AmenitiesEnum> = EnumSet.noneOf(AmenitiesEnum::class.java)
) : Accommodation, Serializable

我用演示值初始化数据库

CREATE TABLE hotels (
id int UNSIGNED NOT NULL AUTO_INCREMENT,
name varchar(125) NOT NULL,
description TEXT NOT NULL,
type ENUM('BED_AND_BREAKFAST', 'SPA') DEFAULT NULL,
rating ENUM('HALF_STAR', 'ONE_STAR', 'TWO_STARS', 'THREE_STARS', 'FOUR_STARS', 'FIVE_STARS') DEFAULT NULL,
amenities SET('POOL','PETS_ALLOWED','PARKING_INCLUDED', 'BAR', 'DISABLED_FRIENDLY', 'FREE_DRINKS', 'WIFI') DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO hotels VALUES (NULL, 'First ever Hotel', 'First hotel ever build. Amazing.', null, 'one_star', 'bar');
SELECT @last := LAST_INSERT_ID();
INSERT INTO rooms VALUES
(NULL, @last, 2, 'QUEEN', 'PETS_ALLOWED'),
(NULL, @last, 1, 'SINGLE', 'PETS_ALLOWED'),
(NULL, @last, 3, 'KING', 'PETS_ALLOWED');

当我启动应用程序并对我得到的数据库发起查询时

... binding parameter [1] as [INTEGER] - [1]
... SQL Error: 1146, SQLState: 42S02
... Table '_database_.hotel_amenities' doesn't exist
... Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not extract ResultSet; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not extract ResultSet (through reference chain: java.util.ArrayList[0]->com.katanox.hotelbooking.domain.room.value.Room["hotel"]->com._.hotelbooking.domain.hotel.value.Hotel["amenities"])]

为什么 MySQL 状态为 Table 'd035b60f.hotel_amenities' doesn't exist,我该如何解决这个问题?将类型更改为 List 而不是 EnumSet 会导致相同的错误。

更新

查看 DEBUG,Hibernate 将其转换为:

select
    amenities0_.hotel_id as hotel_id1_0_0_,
    amenities0_.amenities as amenitie2_0_0_ 
from
    hotel_amenities amenities0_ 
where
    amenities0_.hotel_id=?

我仍在寻找问题的解决方案,任何提示将不胜感激。

【问题讨论】:

  • 因为它是值的集合,不能在单个列中表示(至少从 JPA 的角度来看没有额外的工作)。这也适用于@ElementCollection,它需要知道如何映射,默认情况下它使用外键将其映射到不同的表。

标签: mysql spring hibernate kotlin jdbc


【解决方案1】:

为此,您需要一个自定义 JPA 属性转换器,将其映射到字符串。据我了解,在 JDBC 级别上,这必须表示为逗号分隔的字符串。有关如何使用它的示例,请参阅文档:https://docs.oracle.com/javaee/7/api/javax/persistence/Convert.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2022-01-22
    • 2011-04-03
    • 1970-01-01
    相关资源
    最近更新 更多