How to escape a column name with JPA and Hibernate?

If I have a table mapped to the following entity:

@Entity
public class Services {

	@Id
	private Long id;

	private String name;
	
	private String host;

	private Short port;           
	
	private Sring user;
	
	private String password;
}

When I try to add a new entity, I get this error:

Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into public.services (host, name, password, port, user, id) values ('service.host', 'service', 'password', 707, 'user', 9) was aborted: ERROR: syntax error at or near "user"

How to escape a column name?

You have two choices:

  1. Either you provide the @Column annotation to escape the user property:

    @Entity
    public class Services {
    
         @Id
         private Long id;
    
         private String name;
         
         private String host;
    
         private Short port;           
         
         @Column(name="\"user\"")
         private Sring user;
         
         private String password;
     }
    
  2. Or, you can set the hibernate.globally_quoted_identifiers to true:

      <property name="hibernate.globally_quoted_identifiers" value="true"/>
    

For more details, check out this article.