help me code
help me code

Reputation: 161

Spring batch JdbcCursorItemReader : reading from tables having FK relation

Here's my Reader :

    private static final String SELECT_ALL_BOOKS = "SELECT * FROM BOOKS WHERE COLOR = 'yellow'";

    @Bean
    public JdbcCursorItemReader<BookEntity> itemReader(final DataSource dataSource) {

        return new JdbcCursorItemReaderBuilder<BookEntity>()
                .name("book_reader")
                .sql(SELECT_ALL_BOOKS)
                .dataSource(dataSource)
                .rowMapper(new BeanPropertyRowMapper<>(BookEntity.class))
                .build();

    }

And my entity :

@Entity
@Getter
@Setter
@Table(name = "book")
@AllArgsConstructor
@NoArgsConstructor
public class BookEntity implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_book")
    private Integer idBook;

    @Column(name = "color")
    private String color;

    @Column(name = "page_number")
    private Integer pageNumber;
    
    @Column(name = "read")
    private Boolean read;

    @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
    @JoinColumn(name = "id_author")
    private Author author;

...
...

}

Problem is : with my job executing my step, I'm having the books but with an author = null. So the foreign key is not mapped correctly, all the other String/Integer/Boolean fields are retrieved correctly. I'm new with Spring batch so maybe I'm using a wrong kind of reader.

Any one has an idea about the problem ? Thanks

Upvotes: 0

Views: 8835

Answers (1)

Rakesh
Rakesh

Reputation: 700

Please refer this- You are using JDBC Item reader that is mapped to native columns and properties are binded by BeanPropertyRowMapper

https://docs.spring.io/spring-batch/docs/current/reference/html/readersAndWriters.html#JdbcCursorItemReader

Change the query join with AUTHOR tables as a native query or use JPA readers to support ORM

Below reference will give repository reader

https://docs.spring.io/spring-batch/docs/current/api/org/springframework/batch/item/data/RepositoryItemReader.html

Below example give some idea to implement and its SO references

https://github.com/gpassini/Spring-Batch-RepositoryItemReader-NativeQuery-Example/tree/master/src/main

Upvotes: 2

Related Questions