JPA:如何将 String 持久化到数据库字段中,键入 MYSQL Text [英] JPA: how do I persist a String into a database field, type MYSQL Text
问题描述
要求是用户可以写文章,所以我在mysql数据库中的content
字段选择Text
类型.如何将 Java String
转换为 MySQL Text
The requirement is that the user can write an article, therefore I choose type Text
for the content
field inside mysql database. How can I convert Java String
into MySQL Text
给你Jim Tough
@Entity
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long userId;
private String title;
private String content;
private Integer vote;
//Constructors, setters, getters, equals and hashcode
}
在我的 MYSQL 数据库中,content
是 Text
类型.我希望会有这样的 java.sql.Text
,因为 java.sql.Blob
是一个实际类型,但遗憾的是,它不存在>
In my MYSQL database, content
is type Text
. I was hoping that there would be something like this java.sql.Text
, since java.sql.Blob
is an actual type, but sadly, that does not exist
推荐答案
由于您使用的是 JPA,因此请使用 Lob
批注(以及可选的 Column
批注).这是 JPA 规范对此的说明:
Since you're using JPA, use the Lob
annotation (and optionally the Column
annotation). Here is what the JPA specification says about it:
A Lob
注释指定一个持久属性或字段应该是作为一个大对象持久化到一个数据库支持的大对象类型.便携式应用程序应该使用Lob
映射到 a 时的注解数据库 Lob 类型.Lob 注释可以与Basic
注释.一个 Lob 可能是二进制或字符类型.这Lob 类型是从类型推断的持久字段或属性,以及除了基于字符串和字符的类型默认为 Blob.
9.1.19 Lob Annotation
A
Lob
annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use theLob
annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with theBasic
annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.
所以声明如下:
@Lob
@Column(name="CONTENT", length=512)
private String content;
参考资料
- JPA 1.0 规范:
- 第 9.1.19 节Lob 注释"
这篇关于JPA:如何将 String 持久化到数据库字段中,键入 MYSQL Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!