【问题标题】:Convert String to CLOB in Spring data JPA在 Spring 数据 JPA 中将字符串转换为 CLOB
【发布时间】:2023-03-27 23:57:02
【问题描述】:

我有字符串格式的大文本。我想知道如何将该字符串转换为 CLOB。我正在使用 Spring data JPA,Spring boot。

我尝试过使用

clob.setString(position, string)

【问题讨论】:

  • 请提供您遇到此问题的代码,您刚刚提到了您的尝试。
  • 你遇到了什么错误?
  • 你为什么使用 Spring Data 的低级 API?我们可以退后一步,了解您要做什么吗?你不应该直接使用 Clob。

标签: java spring spring-boot spring-data-jpa


【解决方案1】:

我想简单地回答这个问题。

在 Spring Data JPA 中应该有一个 String 实体,需要在 DB 中保存为 CLOB。所以,实体的 CLOB 列应该是这样的。

@Entity
public class SampleData {
    // other columns 

    @Column(name="SAMPLE", columnDefinition="CLOB NOT NULL") 
    @Lob 
    private String sample;

    // setters and getters
}

那么你应该有一个像下面这样的存储库

public interface SampleDataRepo extends PagingAndSortingRepository<SampleData, Integer> {

}

现在在 Service 方法中,您可以执行以下操作

@Service
public class SampleDataService {

    @Autowire 
    SampleDataRepo repo;

    public SampleData saveSampleData() {
        SampleData sd = new SampleData();
        sd.setSample("longtest");

        repo.save(sd);
    }
}

这就是 String 数据在 DB 中保存为 CLOB 的方式。

【讨论】:

  • 谢谢阿维纳什。我所做的只是在列顶部添加了@Lob,它就像魅力一样。
  • 感谢大家关注这个问题。
  • 我可以用文件类型而不是字符串来做同样的事情吗?
  • 对 CLOB 使用字符串会导致大字符串出现严重的性能问题。我建议改用 java.sql.Clob。
  • @Anass 你能解释一下如何使用 java.sql.Clob 吗?也许为这个问题添加一个答案。谢谢!
猜你喜欢
  • 2012-07-10
  • 2011-01-17
  • 2013-10-02
  • 2012-08-10
  • 2016-02-05
  • 2022-01-23
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多