Home > Net >  Saving JPA @Enumerated value into the database
Saving JPA @Enumerated value into the database

Time:12-08

I am trying to save @Enumerated value into the database:

@Entity
public class Macronutrient {

    public enum Group {
        CARBOHYDRATE, PROTEIN, FAT
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(min = 3, max = 255)
    @NotBlank
    @Column(unique = true)
    private String name;

    @Enumerated(EnumType.STRING)
    private Group group;

    //getters and setters

}

I am sending PATCH request to modify existing Macronutrient:

PATCH /macronutrients
{
    "id": 1,
    "name": "Macronutrient",
    "group": "CARBOHYDRATE"
}

The code responsible for handling the update:

public Macronutrient patchMacronutrient(Macronutrient macronutrient) {
    ...
    if (Objects.nonNull(macronutrient.getGroup())) {
        existingMacronutrient.setGroup(macronutrient.getGroup());
    }
    ...
}

The response I am getting: ERROR: syntax error at or near "group"

Hibernate: 
    update
        public.macronutrient 
    set
        
    group=?,
    name=? where
        id=?

If I DON'T set the group property on Macronutrient then it saved properly. Please help!

CodePudding user response:

A possible reason could be that 'group' is a reserved word (think about "group by" expressions). You may give a try to this: enclose the column name within backticks

@Column(name="`group`")
private Group group;

In JPA 2.0, the syntax is a bit different:

@Column(name="\"group\"")

and see it this works better.

  • Related