无法将String用作SpringData的@Id [英] Can't use String as @Id with SpringData

查看:267
本文介绍了无法将String用作SpringData的@Id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用此类在数据库上创建新表

I want to create new table on my database using this class

@Entity
@Table(name = "currency_rate")
public class CurrencyRate {

    @Id
    private String id;

    @Column(name = "source_currency")
    private String sourceCurrency;

    @Column(name = "target_currency")
    private String targetCurrency;

    @Column(name = "exchange_rate")
    private double exchangeRate;

    @Column
    private Date date;

    @PrePersist
    public void generateID() {            
        this.id = this.date.toString().replace("-", "") + sourceCurrency + targetCurrency;
    }
    //getters, setters
}

当我尝试运行带有属性的应用程序

When I try to run my application with property

spring.jpa.hibernate.ddl-auto=create

我有这个例外

由以下原因引起:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 指定的密钥太长;最大密钥长度为1000个字节

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Specified key was too long; max key length is 1000 bytes

看起来我不能使用Spring作为我的ID?将类型更改为Long可以解决问题,但是我真的很想将String与这个一起使用.根据我的搜索,它应该是完全可行的.

Looks like I can't use Spring as my ID? Changing type to Long solves problem, but I really wanted to go with String with this one. From what I searched, it should be totally doable.

推荐答案

按照 https ://www.tutorialspoint.com/hibernate/hibernate_annotations.htm ,该属性可以通过Column注释详细定义.

As per tutorial from https://www.tutorialspoint.com/hibernate/hibernate_annotations.htm, the attribute can be defined by Column annotation in details.

@Column批注@Column批注用于指定 字段或属性将映射到的列的详细信息.你 可以将列注释与以下最常用的一起使用 属性-

@Column Annotation The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes −

name属性允许显式列的名称 指定.

name attribute permits the name of the column to be explicitly specified.

length属性允许用于映射值的列的大小 尤其是对于String值.

length attribute permits the size of the column used to map a value particularly for a String value.

nullable属性允许在以下情况下将该列标记为NOT NULL: 模式已生成.

nullable attribute permits the column to be marked NOT NULL when the schema is generated.

unique属性允许将该列标记为仅包含 唯一值.

unique attribute permits the column to be marked as containing only unique values.

这里对于您的问题而言重要的是length参数,也许您可​​以尝试如下注释您的ID:

What matters here for your question is length parameter, maybe you can try annotate your id like below:

  @Id
  @Column(length = 100)
  private String id;

这篇关于无法将String用作SpringData的@Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆