有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JPA:如何将字符串持久化到数据库字段中,键入MYSQL文本

要求是用户可以写一篇文章,因此我为mysql数据库中的content字段选择类型Text。如何将Java String转换为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是一个实际的类型,但遗憾的是,它并不存在


共 (3) 个答案

  1. # 1 楼答案

    因为您使用的是JPA,所以可以使用Lob注释(也可以选择使用Column注释)。以下是JPA规范对它的描述:

    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注释”
  2. # 2 楼答案

    对于mysql“文本”:

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

    对于mysql“longtext”:

    @Lob
    private String description;
    
  3. # 3 楼答案

    使用@Lob我总是在MySQL中使用LONGTEXT

    为了得到TEXT,我这样声明(JPA 2.0):

    @Column(columnDefinition = "TEXT")
    private String text
    

    我觉得这样更好,因为我可以直接选择该列在数据库中的文本类型

    对于columnDefinition来说,阅读this也很好

    编辑:请注意Adam Siemionscomment,并在应用columnDefinition = "TEXT"之前检查您正在使用的数据库引擎