1

comparto el la configuración y el pom, el in.csv está en en la raíz. Comprobe la existencia del archivo, que tenía contenido, todo esto desde dentro del programa. En lineMapper() ->mapLine() tengo varios sout con la intención de comprobar unicamente que se accede al método pero entra al método nunca.

La manera más idónea para realizar esto sería utilizar: .lineMapper(new PassThroughLineMapper()) utilizando este mapper de spring pero como no funcionaba cree uno propio para ir depurando porque poniendo el de spring también fallaba

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {


@Bean
public Job job(JobRepository jobRepository, Step step1){
    return new JobBuilder("texto", jobRepository)
            .start(step1)
            .build();
}

@Bean
public Step step1(JobRepository jobRepository, PlatformTransactionManager 
transactionManager){
    return new StepBuilder("step1", jobRepository)
            .<String,String>chunk(10,transactionManager)
            .reader(reader())
            .processor(processor())
            .writer(writer())
            .build();
}
@Bean
public ItemReader<String> reader2(){

    return new FlatFileItemReaderBuilder<String>()
            .name("reader")
            //.resource(new FileSystemResource(file))
            .resource(new FileSystemResource("in.csv"))
            .lineMapper(lineMapper())
            .build();
}



private LineMapper<String> lineMapper() {
    System.out.println("asda");
    return new LineMapper<String>() {
        @Override
        public String mapLine(String line, int lineNumber) throws Exception {
            System.out.println(line);
            System.out.println("line");
            return line;
        }
    };
}

@Bean
public ItemProcessor<String, String> processor(){
    return String::toUpperCase;
}

@Bean
public ItemWriter<String> writer(){
    return new FlatFileItemWriterBuilder<String>()
            .name("write")
            .resource(new FileSystemResource("out.csv"))
            .lineAggregator(new PassThroughLineAggregator<>())
            .build();
}
}

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>batch</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>17</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-batch</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.batch</groupId>
        <artifactId>spring-batch-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>

spring.application.name=texto
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.batch.job.name=texto

Logs:

2024-05-31T18:26:37.092+02:00  INFO 5380 --- [texto] [      restartedMain] com.example.demo.BatchApplication        : No active profile set, falling back to 1 default profile: "default"
2024-05-31T18:26:37.128+02:00  INFO 5380 --- [texto] [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2024-05-31T18:26:37.364+02:00  INFO 5380 --- [texto] [  restartedMain] o.s.b.c.c.annotation.BatchRegistrar      : Finished Spring Batch infrastructure beans configuration in 3 ms.
2024-05-31T18:26:37.445+02:00  INFO 5380 --- [texto] [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2024-05-31T18:26:37.461+02:00  INFO 5380 --- [texto] [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10 ms. Found 0 JPA repository interfaces.
2024-05-31T18:26:37.642+02:00  WARN 5380 --- [texto] [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'jobRegistry' of type [org.springframework.batch.core.configuration.support.MapJobRegistry] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.
2024-05-31T18:26:37.684+02:00  INFO 5380 --- [texto] [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2024-05-31T18:26:37.832+02:00  INFO 5380 --- [texto] [  restartedMain] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:testdb user=SA
2024-05-31T18:26:37.833+02:00  INFO 5380 --- [texto] [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2024-05-31T18:26:37.915+02:00  INFO 5380 --- [texto] [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2024-05-31T18:26:37.965+02:00  INFO 5380 --- [texto] [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.5.2.Final
2024-05-31T18:26:37.992+02:00  INFO 5380 --- [texto] [  restartedMain] o.h.c.internal.RegionFactoryInitiator    : HHH000026: Second-level cache disabled
2024-05-31T18:26:38.214+02:00  INFO 5380 --- [texto] [  restartedMain] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer
2024-05-31T18:26:38.246+02:00  WARN 5380 --- [texto] [  restartedMain] org.hibernate.orm.deprecation            : HHH90000025: H2Dialect does not need to be specified explicitly using 'hibernate.dialect' (remove the property setting and it will be selected by default)
2024-05-31T18:26:38.490+02:00  INFO 5380 --- [texto] [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)
2024-05-31T18:26:38.494+02:00  INFO 5380 --- [texto] [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2024-05-31T18:26:38.517+02:00  INFO 5380 --- [texto] [  restartedMain] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: H2
2024-05-31T18:26:38.566+02:00  INFO 5380 --- [texto] [  restartedMain] .c.a.BatchObservabilityBeanPostProcessor : No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP
2024-05-31T18:26:38.570+02:00  INFO 5380 --- [texto] [  restartedMain] .c.a.BatchObservabilityBeanPostProcessor : No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP
2024-05-31T18:26:38.574+02:00  INFO 5380 --- [texto] [  restartedMain] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2024-05-31T18:26:38.695+02:00  INFO 5380 --- [texto] [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2024-05-31T18:26:38.719+02:00  INFO 5380 --- [texto] [  restartedMain] com.example.demo.BatchApplication        : Started BatchApplication in 1.864 seconds (process running for 2.171)
2024-05-31T18:26:38.728+02:00  INFO 5380 --- [texto] [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2024-05-31T18:26:38.732+02:00  WARN 5380 --- [texto] [ionShutdownHook] o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLNonTransientConnectionException: La base de datos ya esta cerrada (para des-habilitar el cerrado automatico durante el shutdown de la VM, agregue ";DB_CLOSE_ON_EXIT=FALSE" a la URL de conexión)
Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-224]
2024-05-31T18:26:38.732+02:00  INFO 5380 --- [texto] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2024-05-31T18:26:38.734+02:00  INFO 5380 --- [texto] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Prueba a mayores:

@Bean
public CommandLineRunner run(JobLauncher jobLauncher, Job job) {
    return args -> {
        jobLauncher.run(job, new 
JobParametersBuilder().addLong("time", 
 System.currentTimeMillis()).toJobParameters());
    };
}

Y me lanza esta excepción:

org.springframework.jdbc.BadSqlGrammarException: 
PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID, 
JOB_NAME
FROM BATCH_JOB_INSTANCE
WHERE JOB_NAME = ?
and JOB_KEY = ?]
7
  • spring.application.name=batch spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true
    – Cristian
    Commented el 31 may. a las 13:37
  • Parece que no está ahí el nombre del job a ejecutar. Puedes editar tu pregunta y añadir esas propiedades
    – RubioRic
    Commented el 31 may. a las 15:10
  • no lo tenía no, pero aún poniendolo no funciona, ni se llega a ejecutar el job
    – Cristian
    Commented el 31 may. a las 16:29
  • Pero no entiendo, en la pregunta pone que te fallaba en el line mapper. Si no se ejecuta nada, ningún job, ¿cómo te fallaba en esa parte?
    – RubioRic
    Commented el 31 may. a las 17:32
  • ¿Has hecho un clean/install o un build del proyecto al cambiar las propiedades? ¿Has probado a poner un nombre de job que no sea "texto"? ¿Qué pasa si pones "holaMundo"? Debería darte una excepción de job no encontrado
    – RubioRic
    Commented el 31 may. a las 17:34

2 respuestas 2

0

Es un poco difícil determinar qué está fallando exactamente en tu código. Echo a falta el fichero de propiedades de la aplicación.

Te pongo aquí el que yo he utilizado para que los compares

application.properties

spring.application.name=demo
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.batch.job.name=texto

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

BatchApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BatchApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(BatchApplication.class, args);
    }
    
}

BatchConfiguration

@Configuration
public class BatchConfiguration {
    
    @Bean
    public Job job(JobRepository jobRepository, Step step1) {
        return new JobBuilder("texto", jobRepository).start(step1).build();
    }
    
    @Bean
    public Step step1(JobRepository jobRepository,
                      PlatformTransactionManager transactionManager) {
        return new StepBuilder("step1", jobRepository).<String, String>chunk(10, transactionManager)
                                                      .reader(reader())
                                                      .processor(processor())
                                                      .writer(writer())
                                                      .build();
    }
    
    @Bean
    public ItemReader<String> reader() {
        File file = new File("/Users/rubioric/input.txt");
        return new FlatFileItemReaderBuilder<String>().name("reader")
                                                      .resource(new FileSystemResource(file))
                                                      .lineMapper(new PassThroughLineMapper())
                                                      .build();
    }
    
    @Bean
    public ItemProcessor<String, String> processor(){
        return String::toUpperCase;
    }
    
    @Bean
    public ItemWriter<String> writer() {
        File file = new File("/Users/rubioric/output.txt");
        return new FlatFileItemWriterBuilder<String>().name("write")
                                                      .resource(new FileSystemResource(file))
                                                      .lineAggregator(new PassThroughLineAggregator<>())
                                                      .build();
    }
}

Input file

the
animal
instinct
in
me

Output file

THE
ANIMAL
INSTINCT
IN
ME

He preferido usar el constructor de FileSystemResource que acepta un File como argumento para establecer una ruta absoluta de mi computadora local.

El lineMapper PassThroughLineMapper funciona correctamente.

Yo te recomendaría que revisaras tu fichero de propiedades, tu pom.xml y lo que te está mostrando la consola al ejecutar la aplicación. Si no te sale algo parecido a esto de abajo, es que el job ni siquiera se está ejecutando

2024-05-31T14:36:20.979+02:00  INFO 19399 --- [BatchApplication] [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=texto]] launched with the following parameters: [{}]
2024-05-31T14:36:21.063+02:00  INFO 19399 --- [BatchApplication] [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2024-05-31T14:36:21.080+02:00  INFO 19399 --- [BatchApplication] [           main] o.s.batch.core.step.AbstractStep         : Step: [step1] executed in 16ms
2024-05-31T14:36:21.085+02:00  INFO 19399 --- [BatchApplication] [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=texto]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 66ms
0

Lo resolví bajando la versión de spring boot creando así los job y steps con:

 @Autowired
JobBuilderFactory jobBuilderFactory;

@Autowired
StepBuilderFactory stepBuilderFactory;

@Autowired
JobRepository jobRepository;

lo demás sigue igual

3
  • Me extraña mucho que todo sea igual porque para crear un job deberías hacer jobBuilderFactory.get en lugar de new JobBuilder. Y lo mismo para el step. Y tu linemapper no es necesario existiendo PassThroughLineMapper. ¿Y exactamente qué versión has usado de spring-boot? Ya que aceptas tu propia respuesta, al menos deberías completarla un poco.
    – RubioRic
    Commented el 6 jun. a las 6:32
  • No es una solución definitiva pero si temporal, mientras no encuentro una manera de solucionarlo por lo menos puedo lanzar un job, la versión es esta:2.7.4.
    – Cristian
    Commented el 6 jun. a las 18:46
  • Ya, es temporal, pero las respuestas se ponen no solo para indicar que has solucionado tu problema sino para ayudar a otros que tengan uno parecido. Lo que has puesto está incompleto. No basta con poner esaa seis líneas, hay que hacer otras modificaciones y tú has dicho "lo demás sigue igual".
    – RubioRic
    Commented el 7 jun. a las 4:36

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.