JPA:如何将String保存到数据库字段中,键入MYSQL Text [英] JPA: how do I persist a String into a database field, type MYSQL Text

查看:1022
本文介绍了JPA:如何将String保存到数据库字段中,键入MYSQL Text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求是用户可以写文章,因此我为内容字段选择输入文本 mysql数据库。如何将 Java String 转换为 MySQL文本

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 注释(以及可选的注释)。以下是JPA规范所说的:

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:


9.1.19 Lob Annotation



A Lob 注释指定
持久属性或字段应该是
作为大型对象持久保存到
数据库支持的大型对象类型。
当映射到
数据库Lob类型时,便携式应用程序应使用
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 the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆