Issue
I have a model class that is mapped to a postgres database using hibernate. My model class is:
@Entity
@Table(name="USER")
public class User {
@Id
@GeneratedValue
@Column(name="id")
private long id;
@Column(name="username", unique=true)
private String username;
@Column(name="email")
private String email;
@Column(name="created")
private Timestamp created;
public User(long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
}
I try to retrieve the user with username "adam" using the below query:
tx = session.beginTransaction();
TypedQuery<User> query = session.createQuery("FROM User u WHERE u.username = :username", User.class).setParameter("username", "adam");
user = query.getSingleResult();
I get an exception that says:
org.postgresql.util.PSQLException: ERROR: column user0_.id does not exist
My database from bash shell looks like:
How does hibernate map class attributes to table columns? Does it match based on the @Column(name="username") only or does it also try to match based on datatypes and constraints such as unique/auto-increment?
Solution
Solution
In PostgreSQL you have to specify the name of schema like so :
@Table(name="table_name", schema = "myapp")
^^^^^^^^^^^^^^^^
Long Story
you got this error :
org.postgresql.util.PSQLException: ERROR: column user0_.id does not exist
because when you create a database in PostgreSQL, it create a default schema named public, so when you don't specify the name in the Entity then Hibernate will check automatically in the public schema.
Good practices
- Don't use Upper letters in the name of
database,schema,tablesorcolumnsin PostgreSQL. Else you should to escape this names with quotes, and this can cause Syntax errors, so instead you can use :
@Table(name="table_name", schema = "schema_name")
^^^^^^^^^^ ^^^^^^^^^^^
- the keyword USER is reserved keyword in PostgreSQL take a look at
+----------+-----------+----------+-----------+---------+
| Key Word |PostgreSQL |SQL:2003 | SQL:1999 | SQL-92 |
+----------+-----------+----------+-----------+---------+
| .... .... .... .... .... |
+----------+-----------+----------+-----------+---------+
| USER | reserved |reserved | reserved | reserved|
+----------+-----------+----------+-----------+---------+
- to difference between Dto and Entity its good practice to use Entity in the end of the name of your Entity for example
UserEntity
Answered By - Youcef LAIDANI

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.