在创建表时使用hibernate probs,它之前工作正常,但后来经历了一些probs

时间:2014-09-23 12:04:56

标签: java mysql hibernate

我是hibernate的新手,我遇到了一些小问题,我也发布了代码,希望得到所有有经验的人的一些建议。我还发布了我得到的错误。

这是我的模特课

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;
    }
}

这是我的主要课程

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();
    }
}

这是我的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>

我只是从hibernate创建一个表,其中有三列,但这就是我遇到的错误

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

我还有一个疑问。是否有必要在MySql之前创建一个表,因为当我在cfg.xml文件中使用create时它会给我错误,它会自动删除表,我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:2)

错误说

Incorrect column specifier for column 'CarNo'

因为您已将该字段声明为String而非int

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

正如你所说@GeneratedValue(strategy = GenerationType.AUTO) hibernate假设字段car_no为数字并试图创建表格为:

CarNo varchar(255) not null auto_increment

在这里你可以清楚地看到hibernate试图包含对于String数据类型不正确的auto_increment。因此表创建本身失败并出现错误:

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

要解决此问题,请将您的字段更改为适用int的{​​{1}}或long等任何数据类型。

如果您仍想将auto_increment用作car_no,那么您需要使用String生成策略,这是任何标识符的默认策略,因此只需删除生成策略即表示您需要在调用GenerationType.ASSIGNED方法之前,在代码中手动分配标识符。

session.save(Object)

关于属性 hbm2ddl.auto ,当您将其值设置为create时,hibernate会自动运行@Id //@GeneratedValue(strategy = GenerationType.ASSIGNED) -- this line is optional @Column(name = "CarNo") private String car_no; 命令,然后在创建SessionFactory时创建表。如果您不希望每次运行应用程序时都删除表,则必须将其值设置为drop

有关hbm2ddl - Hibernate hbm2ddl.auto possible values and what they do?

的详细信息,请参阅此链接

答案 1 :(得分:0)

@GeneratedValue(strategy = GenerationType.AUTO)不能用于生成string个ID。 如果您想使用string ID,那么只需将@Id放在private String car_no;之上,

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

否则将car_no的数据类型更改为int