-1

I am new to hibernate and I'm experiencing some minor problems to which I have also posted the code, hoping for some suggestions from all the experienced people out there. I have also posted the error which I'm getting.

This is my model class

package com.hibernate.arjun;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Car_Info {

    @Column(name = "CarName")
    private String car_name;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "CarNo")
    private String car_no;
    @Column(name = "CarModel")
    private String car_model;

    public String getCar_name() {
        return car_name;
    }

    public void setCar_name(String car_name) {
        this.car_name = car_name;
    }

    public String getCar_no() {
        return car_no;
    }

    public void setCar_no(String car_no) {
        this.car_no = car_no;
    }

    public String getCar_model() {
        return car_model;
    }

    public void setCar_model(String car_model) {
        this.car_model = car_model;
    }
}

This is my main class

package com.hibernate.arjun;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class MainCar {

    public static void main(String args[]) {
        Car_Info car_Info = new Car_Info();
        car_Info.setCar_name("Ferrari");
        car_Info.setCar_model("Italian");


        SessionFactory factory = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction();

        session.save(car_Info);
        session.getTransaction().commit();
        session.close();
        factory.close();
    }
}

and this is my hibernate.cfg.xml

<hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/CarTable</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>


    <mapping class="com.hibernate.arjun.Car_Info" />

</session-factory>
</hibernate-configuration>

I m just creating a table from hibernate which three columns but then this is the error I'm experiencing

Sep 23, 2014 5:02:36 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists Car_Info
Hibernate: create table Car_Info (CarNo varchar(255) not null auto_increment, CarModel varchar(255), CarName varchar(255), primary key (CarNo))
Sep 23, 2014 5:02:36 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: create table Car_Info (CarNo varchar(255) not null auto_increment, CarModel varchar(255), CarName varchar(255), primary key (CarNo))
Sep 23, 2014 5:02:36 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Incorrect column specifier for column 'CarNo'
Sep 23, 2014 5:02:36 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Car_Info (CarModel, CarName) values (?, ?)
Sep 23, 2014 5:02:36 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Sep 23, 2014 5:02:36 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'cartable.car_info' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
    at com.hibernate.arjun.MainCar.main(MainCar.java:19)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'cartable.car_info' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
    at com.mysql.jdbc.Util.getInstance(Util.java:383)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4208)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4140)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2597)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2758)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2826)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 22 more

I have also one more doubt. Is it necessary to create a table before in MySql, because when I use create in the cfg.xml file it gives me error, it automatically deletes the table, what should I do?

Thank you!

Travenin
  • 1,511
  • 1
  • 13
  • 24
arjun narahari
  • 176
  • 6
  • 26

2 Answers2

2

The error says

Incorrect column specifier for column 'CarNo'

because you have declared the field as String instead of int:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CarNo")
private String car_no;

As you said @GeneratedValue(strategy = GenerationType.AUTO) hibernate assumed that the field car_no as a number and tried to create your table as:

CarNo varchar(255) not null auto_increment

Here you can clearly see that hibernate is trying to include auto_increment which is not correct for String data type. So the table creation itself failed with error :

ERROR: HHH000389: Unsuccessful: create table Car_Info (CarNo varchar(255) not null auto_increment, CarModel varchar(255), CarName varchar(255), primary key (CarNo))

To fix the issue change your field to any data type like int or long etc where the auto_increment is applicable.

If you still want to use car_no as String then you need to use the GenerationType.ASSIGNED generation strategy which is the default strategy for any identifiers so just removing the generation strategy means you need to assign the identifier manually in your code before calling session.save(Object) method.

@Id
//@GeneratedValue(strategy = GenerationType.ASSIGNED) -- this line is optional
@Column(name = "CarNo")
private String car_no;

Regarding the property hbm2ddl.auto, when you set its value to create then hibernate automatically runs the drop commands and then creates the tables while creating SessionFactory. You have to set its value to update if you don't want to drop the tables every time when you run the application.

Refer to this link for more details on hbm2ddl - Hibernate hbm2ddl.auto possible values and what they do?

Community
  • 1
  • 1
Chaitanya
  • 15,403
  • 35
  • 96
  • 137
0

@GeneratedValue(strategy = GenerationType.AUTO) cannot be used to generate string id. If you want use string Id then just put @Id over private String car_no; like,

   @Id
    @Column(name = "CarNo")
    private String car_no;

otherwise change the datatype of car_no to int.

Rohan
  • 3,068
  • 1
  • 20
  • 26