我想使用这个类在我的数据库上创建新表
@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/