1

我有一个带有DESCRIPTIONCLOB 类型列的表的 Oracle 数据库。

我的 POJO 看起来像这样:

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.data.annotation.Id;

import lombok.Data;

@Data
@Table("MY_ITEMS")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyItem {

    @Column("ID") @Id Long id;
    @Column("DESCRIPTION") String description;
}

我的存储库看起来像这样

import java.util.List;

import com.myapp.mymodel.MyItem;

import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;

public interface MyItemsRepository extends CrudRepository<MyItem, Long> {

    // other methods deleted...

    @Query(
        "select m.ID"
            + ", m.DESCRIPTION"
        + " from MY_ITEM m "
    )
    List<MyItem> findMyItems();
}

当我调用存储库方法时,我收到一条错误消息,指出没有将 CLOB 转换为字符串的转换器。

任何帮助表示赞赏。

4

1 回答 1

2

这里有一个很好的例子可以解决这个问题: https ://github.com/spring-projects/spring-data-examples/tree/master/jdbc/basics

该解决方案相当于添加一个配置,该配置注册一个可以将CLOB数据提取到String属性的转换器

import java.sql.Clob;
import java.sql.SQLException;
import java.util.Arrays;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.jdbc.core.convert.JdbcCustomConversions;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.relational.core.mapping.Embedded.Nullable;

@Configuration
@EnableJdbcRepositories
public class AggregateJdbcConfiguration extends AbstractJdbcConfiguration {

    @Override
    public JdbcCustomConversions jdbcCustomConversions() {

        return new JdbcCustomConversions(Arrays.asList(new Converter<Clob, String>() {

            @Nullable
            @Override
            public String convert(Clob clob) {

                try {

                    return Math.toIntExact(clob.length()) == 0 //
                            ? "" //
                            : clob.getSubString(1, Math.toIntExact(clob.length()));

                } catch (SQLException e) {
                    throw new IllegalStateException("Failed to convert CLOB to String.", e);
                }
            }
        }));
    }
}

这里有一些我最喜欢的关于这个主题的视频

https://www.youtube.com/watch?v=EaHlancPA14&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=3&t=0s

https://www.youtube.com/watch?v=GOSW911Ox6s&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=4&t=59s

https://www.youtube.com/watch?v=AnIouYdwxo0&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=5&t=2730s

还有几篇博文

https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates

https://spring.io/blog/2018/09/17/introducing-spring-data-jdbc

于 2020-02-03T15:13:08.090 回答