mysql - 不能将 String 作为 @Id 与 Spring Data 一起使用

标签 mysql spring spring-data

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

@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

我遇到了这个异常

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

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

最佳答案

根据 https://www.tutorialspoint.com/hibernate/hibernate_annotations.htm 中的教程,该属性可以通过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 attribute permits the name of the column to be explicitly specified.

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

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

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

这里对你的问题重要的是 length 参数,也许你可以尝试像下面这样注释你的 id:

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

关于mysql - 不能将 String 作为 @Id 与 Spring Data 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660942/

相关文章:

c# - Microsoft Visual Studio SQL 服务器连接 - 无效指针

spring - 如何忽略自定义 Spring 租户

java - 跨越多个存储库的 Spring Data Transaction

java - 如何使用@Query 注释构建查询?

mysql - 无法在jsf中编辑数据库表

mysql - 提供者 Entity Framework MySQL 中出现错误

php - 尝试使用 PHP 从 mysql 中使用纬度和经度查找商店位置

spring - 在 Angular 5 中接收 Flux SSE

java - Spring mongo 只写字段

java - Spring Data findOne() NullPointerException