Text Field using Hibernate Annotation

谁说胖子不能爱 提交于 2019-12-18 10:15:26

问题


I am having trouble setting the type of a String, it goes like

public void setTextDesc(String textDesc) {
    this.textDesc = textDesc;
}

@Column(name="DESC")
@Lob
public String getTextDesc() {
    return textDesc;
}

and it didn't work, I checked the mysql schema and it remains varchar(255), I also tried,

@Column(name="DESC", length="9000")

or

@Column(name="DESC")
@Type(type="text")

I am trying to make the type to be TEXT, any idea would be well appreciated!


回答1:


You said "I checked the mysql schema and it remains varchar(255)" - did you expect Hibernate to automatically alter your database? It won't. Even if you have hibernate.hbm2ddl.auto set, I don't believe Hibernate would alter the existing column definition.

If you were to generate new database creation script, @Lob should generate "TEXT" type column if you don't specify length explicitly (or if you do and it's less that 65536). You can always force that by explicitly declaring type in @Column annotation, though keep in mind that's not portable between databases:

@Column(name="DESC", columnDefinition="TEXT")



回答2:


There is a way to set the default mapping for "String" type to be set to "text" type in the database.

Save the following file in the package where you have your entities. Please change the package name as well.

This will set all "String" type fields to "text" type in the db for the package specified.

package-info.java

@TypeDefs({
      @TypeDef(name="string",defaultForType=java.lang.String.class,typeClass=org.hibernate.type.TextType.class)
})

package com.package.app;

import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;


来源:https://stackoverflow.com/questions/1281188/text-field-using-hibernate-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!