skip to Main Content

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...

2

Answers


  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();
    
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search