Maksim
Maksim

Reputation: 185

Hibernate: MySQL

I have a class with the following fields:

@Entity
@Table(name = "customers")
public class Customer {
    @Id
    int id;
    String name;
    String items;
    String when;
    String where;
    ... // getters and setters
}

I've created a table in MySQL database called "customers":
Columns:

id int(11) PK 
name varchar(45) 
items varchar(45) 
when varchar(45) 
where varchar(45)

And I'm trying to add the class into the database like this:

Customer customer = new Customer();
customer.setId(1);
customer.setName("Rextuz");
customer.setItems("red_rose1");
customer.setWhen("1_1_2015");
customer.setWhere("len");
... // getting a session factory
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(customer);
session.getTransaction().commit();
session.close();

I'm getting the following error:

Hibernate: insert into customers (items, name, when, where, id) values (?, ?, ?, ?, ?)
дек 14, 2014 12:20:17 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
дек 14, 2014 12:20:17 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'when, where, id) values ('red_rose1', 'Rextuz', '1_1_2015', 'len', 1)' at line 1

Are there any ideas how to fix it? Im using org.hibernate.dialect.MySQLDialect

Upvotes: 2

Views: 143

Answers (1)

atish shimpi
atish shimpi

Reputation: 5023

You are using SQL keywords when and where in your Customer class, that's why exception came when hibernate fire your query on sql database, if possible you have change the name of Customer class properties.

OR

You have to do something like following code.

public class Customer {
  .... 
   @Column("TX_WHEN")
    String when;

    @Column("TX_WHERE")
    String where;
    ... // getters and setters
}

and you have to change your customers table accordingly.

Upvotes: 3

Related Questions