代码之家  ›  专栏  ›  技术社区  ›  mshafrir

Hibernate没有为MySQL中的CLOB创建正确的字段

  •  1
  • mshafrir  · 技术社区  · 15 年前

    我的实体中有一个字符串

    @Column(length=40000)
    @Lob
    private String introText;
    

    在我的MySQL数据库中,Hibernate为内文创建的列是VARCHAR(255),它不与列长度或@ Lob注释保持一致。有什么想法吗?我对休眠相对比较陌生,所以我想知道是否缺少其他设置或配置。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Arthur Ronald    15 年前

    完成以下操作后

    // Notice without @Lob
    @Column(length=4000)
    private String getIntroText() {
        return this.introText;
    }
    

    在剧本里,我明白了

    IntroText TEXT
    

    所以它不能像预期的那样工作。所以我的建议是:改为使用columnDefinition属性

    它允许您定义用于定义列类型的确切DDL

    @Lob
    @Column(columnDefinition="TEXT (4000)")
    private String getIntroText() {
        return this.introText;
    }
    

    现在它工作得很好!如果你想,你可以测试

    AnnotationConfiguration configuration = new AnnotationConfiguration();
    
    configuration
        .addAnnotatedClass(<YOUR_ENTITY_GOES_HERE>.class)
        .setProperty(Environment.HBM2DDL_AUTO, "create")
        .setProperty(Environment.USER, "<USER_GOES_HERE>")
        .setProperty(Environment.PASS, "<USER_PASS_GOES_HERE>")
        .setProperty(Environment.SHOW_SQL, "true")
        .setProperty(Environment.FORMAT_SQL, "true")
        // Set up your dialect according to the Target MySQL
        .setProperty(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect")
        .setProperty(Environment.DRIVER, "com.mysql.jdbc.Driver")
        .setProperty(Environment.URL, "jdbc:mysql://127.0.0.1:3306/<YOUR_SCHEMA_GOES_HERE>");
    
    SchemaExport schema = new SchemaExport(configuration);
    schema.setOutputFile("schema.sql");
    
    schema.create(true, true);
    

    只是一个建议:如果可能,将注释配置放在getter方法中,而不是成员字段中。Hibernate使用代理来完成您的工作。当在getter方法中使用注释配置时,它工作得很好。

    当做,