0

Is it possible with the entity manager to save the name of the enum without using the name method? I need it because sometimes my enum will be null and then the name method would return a nullpointer. Now I have to do this:

entityManager.createNativeQuery(
                "INSERT INTO car(enum_column) " +
                        "VALUES(enumColumn)")
        .unwrap(NativeQuery.class)
        .setParameter("enumColumn", entity.getEnumColumn.name)
        .executeUpdate();

i need to do this something like this and set enum name:

entityManager.createNativeQuery(
                "INSERT INTO car(enum_column) " +
                        "VALUES(enumColumn)")
        .unwrap(NativeQuery.class)
        .setParameter("enumColumn", entity.getEnumColumn)
        .executeUpdate();

unfortunelly, now result is : \xaced00057e72002c636f6dffddffd...

pawello12
  • 17
  • 5

2 Answers2

1

The easiest one, still quite readable:

entityManager.createNativeQuery(
    "INSERT INTO car(enum_column) " +
    "VALUES(:enumColumn)")
    .unwrap(NativeQuery.class)
    .setParameter("enumColumn", entity.getEnumColumn() == null ? null : entity.getEnumColumn().name())
    .executeUpdate();
Yahor Barkouski
  • 1,361
  • 1
  • 5
  • 21
1

Yes, it is possible to save the name of the enum without using the name method. You can use the Enum.toString() method instead. The toString() method returns the string representation of the enum constant, which is its name.

entityManager.createNativeQuery(
    "INSERT INTO car(enum_column) " +
            "VALUES(:enumColumn)")
.unwrap(NativeQuery.class)
.setParameter("enumColumn", entity.getEnumColumn != null ? entity.getEnumColumn.toString() : null)
.executeUpdate();
  • ohh so simple and so good answer, thank You ! – pawello12 Jun 27 '23 at 10:53
  • All three of your recent answers here appear likely to have been entirely or partially written by AI (e.g., ChatGPT). Please be aware that [posting AI-generated content is not allowed here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it. – NotTheDr01ds Jul 05 '23 at 11:28
  • **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. The moderation team can use your help to identify quality issues. – NotTheDr01ds Jul 05 '23 at 11:28