java 用于 TEXT 的 Hibernate 列注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43500155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:29:24  来源:igfitidea点击:

Hibernate column annotation for TEXT

javaspringhibernatespring-bootjpa

提问by Martijn Jansen

I have a spring MVC boot application with a MySQL database and I'm trying to get a TEXT field in my database. I have the following code:

我有一个带有 MySQL 数据库的 spring MVC 启动应用程序,我正在尝试在我的数据库中获取一个 TEXT 字段。我有以下代码:

Member.java

会员.java

@Entity
public class Member {
private Long id;
private String name;

@Column(columnDefinition = "TEXT")
private String biography;

private String country;
private String state;
private String city;
private Date dateOfBirth;
private String gender;

//Getters and setters

application.properties

应用程序属性

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.datasource.url=jdbc:mysql://localhost:3306/wave
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.h2.console.enabled=true

And here is the Hibernate it creates

这是它创建的 Hibernate

Hibernate: drop table if exists member
Hibernate: create table member (id bigint not null auto_increment, biography varchar(255), city varchar(255), country varchar(255), date_of_birth date, gender varchar(255), name varchar(255), state varchar(255), primary key (id)) ENGINE=InnoDB

It still sets it as a varchar(255). Can anyone help me with this issue? Thank you in advance.

它仍然将其设置为 varchar(255)。谁能帮我解决这个问题?先感谢您。

回答by Roll

You can use @Lobfrom javax.persistence... it's more elegant:

您可以@Lobjavax.persistence使用...它更优雅:

@Column
@Lob
public String getDescription() {...

回答by Maciej Kowalski

In org.hibernate.dialect.MySQLDialectclass there is a line:

org.hibernate.dialect.MySQLDialect课堂上有一行:

registerColumnType( Types.CLOB, 65535, "text" );

So based on that if you define your field like this:

因此,如果您像这样定义您的字段,则基于此:

@Column(length = 65535, columnDefinition = "text")
private String biography;

it should do the trick.

它应该可以解决问题。

回答by dmbdnr

Leaving the column definition could solve the problem (Only annotate with @Column, hibernate is clever to figure it out), but varcharis the replacement of textin newer versions of sql servers, so I think there is nothing wrong with using varchar. (255) is the default length.

保留列定义可以解决问题(只用 注释@Column,hibernate 很聪明地想出来),但在较新版本的 sql 服务器中varchar是替换text,所以我认为使用varchar. (255) 是默认长度。