gpt4 book ai didi

java - 在 InheritanceType.JOINED 中使用 AttributeConverter 映射 MySQL ENUM 在 Hibernate 5.3.6 (JPA 2.1+) : No enum constant 上抛出 IllegalArgumentException

转载 作者:行者123 更新时间:2023-11-30 05:21:56 27 4
gpt4 key购买 nike

我正在映射继承层次结构,如下所示:

enter image description here

这里的问题是,数据库包含分别代表人员、俱乐部和竞技场的单字符枚举值“P”、“C”和“A”,但要使用的 Java 枚举值应该是人物、俱乐部和竞技场。

这需要使用 AttributeConverter 来执行 DB 值 - Java 枚举转换(请参阅下面的映射):

联系实体:

@Entity
@Table(name="Contacts")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Contact extends BaseIdEntity
{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column
protected Integer id;

@Convert(converter=ContactTypeConverter.class) // <-- !!! ... see below
@Enumerated(EnumType.STRING)
@Basic(optional=false)
@Column
protected ContactType type; // actually a discriminator, but for JOINED inheritance, it is not required to annotate the class with @DiscriminatorColumn

...
}

联系人类型枚举:

public enum ContactType
{
PERSON, <-- fully written, but data is single-char
CLUB,
ARENA;
}

人实体:

@Entity
@Table(name="Persons")
public class Person extends Contact
{
private static final long serialVersionUID = 1L;

@Basic(optional=false)
@Column(name="first_name")
private String firstName;

@Basic(optional=false)
@Column(name="last_name")
private String lastName;

...
}

俱乐部实体:

@Entity
@Table(name="Clubs")
public class Club extends Contact
{
private static final long serialVersionUID = 1L;

@Basic(optional=false)
@Column
private String name;

@Basic(optional=false)
@Column
private String code;

@Basic
@Column(name="website_url")
private String websiteUrl;

...
}

竞技场实体:

@Entity
@Table(name="Arenas")
public class Arena extends Contact
{
private static final long serialVersionUID = 1L;

@Basic(optional=false)
@Column
private String name;

@Basic
@Column
private Integer capacity;

...
}

ContactType 的属性转换器:

@Converter( autoApply = false )
public class ContactTypeConverter implements AttributeConverter<ContactType, String>
{
@Override
public String convertToDatabaseColumn( ContactType contactType )
{
System.out.println( "convertToEntityAttribute(" + contactType + ")" );

switch ( contactType )
{
case PERSON:
return "P";

case CLUB:
return "C";

case ARENA:
return "A";

default:
throw new IllegalArgumentException( "Unknown enum value: " + contactType );
}
}

@Override
public ContactType convertToEntityAttribute( String value )
{
System.out.println( "convertToEntityAttribute(\"" + value + "\")" );

switch ( value )
{
case "P":
return PERSON;

case "C":
return CLUB;

case "A":
return ARENA;

default:
throw new IllegalArgumentException( "Unknown DB value: " + value );
}
}
}

这是 MySQL 的 DDL + 数据:

CREATE TABLE `Contacts`(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`type` ENUM('P', 'C', 'A') NOT NULL,
PRIMARY KEY (`id`));

CREATE TABLE `Arenas` (
`id` INT(11) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`capacity` INT(11) NULL,
PRIMARY KEY (`id`),
CONSTRAINT `arenas_contacts_fk`
FOREIGN KEY (`id`)
REFERENCES `Contacts` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE);

CREATE TABLE `Clubs` (
`id` INT(11) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`code` VARCHAR(5) NOT NULL,
`website_url` VARCHAR(64) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `clubs_contacts_fk`
FOREIGN KEY (`id`)
REFERENCES `Contacts` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE);

CREATE TABLE `Persons` (
`id` INT(11) NOT NULL,
`first_name` VARCHAR(50) NOT NULL,
`last_name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `persons_contacts_fk`
FOREIGN KEY (`id`)
REFERENCES `Contacts` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE);

数据:

INSERT INTO `Contacts` (`id`, `type`) VALUES
( 1, 'P'),
( 2, 'P'),
( 3, 'P'),
( 26, 'P'),
( 99, 'P'),
(101, 'C'),
(102, 'C'),
(103, 'C'),
(201, 'A'),
(202, 'A'),
(203, 'A');

INSERT INTO `Persons` (`id`, `first_name`, `last_name`) VALUES
( 1, 'Kay', 'Wundrak'),
( 2, 'Joe', 'Locke'),
( 3, 'Ahmed', 'Thiab'),
( 26, 'Seb', 'Gottwalk'),
( 99, 'Test', 'Test');

INSERT IGNORE INTO `Clubs` (`id`, `name`, `code`) VALUES
(101, 'TV Dieburg', 'DIEB'),
(102, 'SC Rist Wedel', 'RIST'),
(103, 'BBG Herford', 'HERF');

INSERT IGNORE INTO `Arenas` (`id`, `name`, `capacity`) VALUES
(201, 'Schlossgartenhalle', NULL),
(202, 'Steinberghalle', NULL),
(203, 'Halle am Gymnasium', NULL);

我查阅了很多资料,例如

https://www.nurkiewicz.com/2013/06/mapping-enums-done-right-with-convert.html [主要]

https://thoughts-on-java.org/jpa-21-type-converter-better-way-to/

https://thoughts-on-java.org/jpa-21-how-to-implement-type-converter/

https://www.baeldung.com/jpa-persisting-enums-in-jpa

http://eloquentdeveloper.com/2016/07/18/persisting-enums-using-jpa-attribute-converter/

都说一样,但是不行。加载人员列表时,我得到:

Caused by: java.lang.IllegalArgumentException: No enum constant net.bbstats.entity.ContactType.P
at java.lang.Enum.valueOf(Enum.java:238)
at org.hibernate.type.descriptor.java.EnumJavaTypeDescriptor.fromName(EnumJavaTypeDescriptor.java:84)
at org.hibernate.metamodel.model.convert.internal.NamedEnumValueConverter.toDomainValue(NamedEnumValueConverter.java:39)
at org.hibernate.metamodel.model.convert.internal.NamedEnumValueConverter.readValue(NamedEnumValueConverter.java:69)
at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:250)
at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:119)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:91)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3007)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1746)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1672)
at org.hibernate.loader.Loader.getRow(Loader.java:1561)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:731)
at org.hibernate.loader.Loader.processResultSet(Loader.java:990)
at org.hibernate.loader.Loader.doQuery(Loader.java:948)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
at org.hibernate.loader.Loader.doList(Loader.java:2689)
at org.hibernate.loader.Loader.doList(Loader.java:2672)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506)
at org.hibernate.loader.Loader.list(Loader.java:2501)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1508)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505)
at org.hibernate.query.Query.getResultList(Query.java:135)
at net.bbstats.framework.service.Repository.findByNamedQuery(Repository.java:184)
at net.bbstats.framework.service.BaseEntityService.findByNamedQuery(BaseEntityService.java:382)
at net.bbstats.framework.service.BaseEntityService.findByNamedQuery(BaseEntityService.java:368)
at net.bbstats.framework.service.BaseEntityService.findByNamedQuery(BaseEntityService.java:344)
at net.bbstats.framework.service.BaseEntityService.findAllByQueryWithFetchGraph(BaseEntityService.java:300)
... 179 more

看行:

java.lang.IllegalArgumentException:没有枚举常量 net.bbstats.entity.ContactType.P

没有真正正确转换或根本没有转换...?

问题:

这里出了什么问题?我几乎 100% 确定映射是正确的...

-> 这是一个 Hibernate 错误吗? 是因为继承映射吗?也许不适用于 InheritanceType.JOINED

无论如何,一个观察结果是,无论如何,属性转换器永远不会被调用,即 ContactTypeConverter 中不会到达任何断点,并且不会出现任何系统输出曾经打印到控制台/日志。

设置:WildFly 14.0.1.Final、Hibernate 5.3.6.Final

最佳答案

根据this .

JPA explicitly disallows the use of an AttributeConverter with an attribute marked as @Enumerated. So, when using the AttributeConverter approach, be sure not to mark the attribute as @Enumerated.

关于java - 在 InheritanceType.JOINED 中使用 AttributeConverter 映射 MySQL ENUM 在 Hibernate 5.3.6 (JPA 2.1+) : No enum constant 上抛出 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59422281/

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