jpa使用@CollectionTable创建表

本地使用最新版本mysql

mysql  Ver 8.0.21 for Linux on x86_64 (MySQL Community Server - GPL)

配置文件application.yaml

复制代码
server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://bigdata1:3306/stream?createDatabaseIfNotExist=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false&AllowPublicKeyRetrieval=True
    username: root
    password: 123456
  jpa:
    properties:
      hibernate:
        show_sql: true
        format_sql: true
    hibernate:
      ddl-auto: update
复制代码

刚开始mysql连接没有加AllowPublicKeyRetrieval=True,启动报错

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Public Key Retrieval is not allowed

最简单的解决方法是在连接后面添加 allowPublicKeyRetrieval=true

文档中(https://mysql-net.github.io/MySqlConnector/connection-options/)给出的解释是:

如果用户使用了 sha256_password 认证,密码在传输过程中必须使用 TLS 协议保护,但是如果 RSA 公钥不可用,可以使用服务器提供的公钥;可以在连接中通过 ServerRSAPublicKeyFile 指定服务器的 RSA 公钥,或者AllowPublicKeyRetrieval=True参数以允许客户端从服务器获取公钥;但是需要注意的是 AllowPublicKeyRetrieval=True可能会导致恶意的代理通过中间人攻击(MITM)获取到明文密码,所以默认是关闭的,必须显式开启。

实体类:

复制代码
@Data
@Entity
@Table(name = "stream_job")
public class StreamJob {
    @Id
    @Column(name = "job_id")
    private String id;

    /**
     * job扩展参数
     */
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name = "stream_job_extend_params",
            joinColumns = @JoinColumn(name = "job_id"))
    @MapKeyColumn(name = "`key`")
    @Column(name = "value", length = 10240)
    private Map<String, String> extendParams = new HashMap<>();

}
复制代码

启动程序可看到成功创建表

复制代码
Hibernate: 
    
    create table stream_job (
       job_id varchar(255) not null,
        primary key (job_id)
    ) engine=InnoDB
Hibernate: 
    
    create table stream_job_extend_params (
       job_id varchar(255) not null,
        value varchar(10240),
        `key` varchar(255) not null,
        primary key (job_id, `key`)
    ) engine=InnoDB
Hibernate: 
    
    alter table stream_job_extend_params 
       add constraint FK89alxepghu8fe3rxwyxbric1b 
       foreign key (job_id) 
       references stream_job (job_id)
复制代码

奇怪的是部署到生产环境,stream_job_extend_params这个表始终没有创建成功

最终定位是由于生产创建表使用的是MyISAM存储引擎,而我本地默认使用InnoDB存储引擎,MyISAM存储引擎主键最多不能超过1000个字节,而job_id varchar(255),`key` varchar(255),(255+255)*3 > 1000

原文地址:https://www.cnblogs.com/vip-nange/p/13945812.html