【问题标题】:Can't use String as @Id with SpringData不能将 String 作为 @Id 与 Spring Data 一起使用
【发布时间】:2018-11-12 15:06:52
【问题描述】:

我想使用这个类在我的数据库上创建新表

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

当我尝试使用属性运行我的应用程序时

spring.jpa.hibernate.ddl-auto=create

我遇到了这个异常

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

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

【问题讨论】:

标签: mysql spring spring-data


【解决方案1】:

根据https://www.tutorialspoint.com/hibernate/hibernate_annotations.htm的教程,可以通过Column注解详细定义属性。

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

name 属性允许明确显示列的名称 指定。

length 属性允许用于映射值的列的大小 特别是对于字符串值。

nullable 属性允许将列标记为 NOT NULL,当 架构已生成。

unique 属性允许将列标记为仅包含 独特的价值。

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

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

【讨论】:

    猜你喜欢
    • 2012-09-08
    • 2019-03-07
    • 2014-03-10
    • 2014-10-21
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多