Search code examples
mysqlstringhibernatevarchardialect

Using registerColumntype for hibernate to use mediumtext in MySQL


I encountered the following error when trying to insert content to MySQL using hibernate, the error is due to one of the columns being a "mediumtext" data type in MysQL, but in my entity class I declare the field as String.

Initial sessionFactory creation failed.org.hibernate.HibernateException: Wrong column type in db_test.articles for column content. Found: mediumtext, expected: varchar(255)
Exception in thread "main" java.lang.ExceptionInInitializerError

I have found some posts on google search, and have copied the following class into my "src/main/java/persistence directory:

public class MySQLDialect extends org.hibernate.dialect.MySQLDialect
{
    public MySQLDialect()
    {
        super();
        System.out.println("MyMySQLDialect created new instance!");
    }

    protected void registerVarcharTypes() {
        System.out.println("MyMySQLDialect: registering VarCharTypes");
        registerColumnType(Types.VARCHAR, 16777215, "mediumtext");
        registerColumnType(Types.VARCHAR, 65535, "text");
        registerColumnType(Types.VARCHAR, 255, "varchar($1)");
        registerColumnType(Types.LONGNVARCHAR, "longtext");
    }
}

but I don't know how to let Hibernate know this custom data type. thanks


Solution

  • I solved my problem by using "columndefinition = mediumtext", because I figured out to use the "update" feature in Hibernate to automatically update MySQL column data types. Everything works now.