Hibernate将java int转换为mysql整数

时间:2015-07-20 14:06:38

标签: mysql hibernate dialect

我的实体类有一个如下所示的列:

@Entity
@Table(name = "addons")
public class AddonsEntity {
    private int id;
    private String name;
    private BigDecimal price;
    private int addonGroupId;
    private int order;
    private AddonGroupsEntity addonGroupsByAddonGroupId;

    @Id
    @Column(name = "id", nullable = false, insertable = true, updatable = true)
    @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy="increment")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

这转换为sql,如:

创建表格插件(id 整数非空,....);

由于mysql中没有类似整数的内容,因此抛出错误。

版本:

'org.hibernate', name: 'hibernate-core', version: '4.3.10.Final'
'org.hibernate', name: 'hibernate-c3p0', version: '4.3.10.Final'
'mysql', name: 'mysql-connector-java', version: '5.1.35'
 Mysql Server version: 5.6.25 Homebrew
 Java 1.8

SQL翻译:

create table addons (
        id integer not null,
        addon_group_id integer not null,
        name varchar(200) not null,
        order integer not null,
        price decimal(2,0) not null,
        addonGroupsByAddonGroupId_id integer not null,
        primary key (id)
    )

ERROR:

2015-07-21 01:26:13 [] ERROR [Scanner-1] o.h.t.h.SchemaExport [SchemaExport.java:426] HHH000389: Unsuccessful: create table addons (id integer not null, addon_group_id integer not null, name varchar(200) not null, order integer not null, price decimal(2,0) not null, addonGroupsByAddonGroupId_id integer not null, primary key (id)) 
2015-07-21 01:26:13 [] ERROR [Scanner-1] o.h.t.h.SchemaExport [SchemaExport.java:427] 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 'order integer not null,price decimal(2,0) not null,addonGroups' at line 5 

2 个答案:

答案 0 :(得分:2)

问题不在于integer。问题出在create语句中。正如您在create语句order中看到的那样,使用order integer not null,...创建了列,其中ORDER是Mysql中的保留字。

如果您正在使用注释,则解决方案

@Column(name = "[ORDER]", nullable = false)
    public int getOrder() {
        return this.order;
    }

@Column(name = '"ORDER"', nullable = false)
    public int getOrder() {
        return this.order;
    }

如果您使用的是hbm文件,解决方法是:

   <property name="order">
            <column name="[ORDER]" not-null="true" />
   </property>

或者

<property name="order">
    <column name='"ORDER"' length="255" not-null="true" />
</property>

答案 1 :(得分:0)

在我看来,您的应用程序未正确配置为使用MySQLDialect。如何正确配置Hibernate取决于您执行它的环境,所以请查看正确的文档。

此问题的起点可能是Stack Overflow Question“Why do I need to configure the SQL dialect of a data source?