2017-06-18 109 views
0
package com.batch.hibernate.config; 

import javax.sql.DataSource; 

import org.springframework.batch.core.Job; 
import org.springframework.batch.core.Step; 
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; 
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; 
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; 
import org.springframework.batch.core.launch.support.RunIdIncrementer; 
import org.springframework.batch.core.step.skip.SkipPolicy; 
import org.springframework.batch.item.database.JdbcBatchItemWriter; 
import org.springframework.batch.item.file.FlatFileItemReader; 
import org.springframework.batch.item.file.LineMapper; 
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; 
import org.springframework.batch.item.file.mapping.DefaultLineMapper; 
import org.springframework.batch.item.file.mapping.FieldSetMapper; 
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; 
import org.springframework.batch.item.file.transform.LineTokenizer; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.core.env.Environment; 
import org.springframework.core.io.FileSystemResource; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 

import com.batch.hibernate.job.FileVerificationSkipper; 
import com.batch.hibernate.job.UserItemPreparedStatementSetter; 
import com.batch.hibernate.job.UserItemProcessor; 
import com.batch.hibernate.model.User; 

@Configuration 
@EnableBatchProcessing 
/*@ComponentScan(basePackages = { "com.batch.hibernate" }) 
@PropertySource("classpath:application.properties")*/ 
public class BatchConfiguration { 

    @Autowired 
    private Environment environment; 

    @Autowired 
    public JobBuilderFactory jobBuilderFactory; 

    @Autowired 
    public StepBuilderFactory stepBuilderFactory; 

    @Autowired 
    public DataSource dataSource; 

    @Bean 
    public DataSource dataSource(){ 
     final DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName(environment.getProperty("connection.driver_class")); 
     dataSource.setUrl(environment.getProperty("connection.url")); 
     dataSource.setUsername(environment.getProperty("connection.username")); 
     dataSource.setPassword(environment.getProperty("connection.password")); 
     return dataSource; 
    } 

    @Bean 
    public FlatFileItemReader<User> reader(){ 
     FlatFileItemReader<User> reader = new FlatFileItemReader<User>(); 
     reader.setResource(new FileSystemResource(environment.getProperty("local.filesystem.path"))); 
     reader.setLinesToSkip(Integer.valueOf(environment.getProperty("header.lines.in.file"))); 
     LineMapper<User> userLineMapper = createUserLineMapper(); 
     reader.setLineMapper(userLineMapper); 
     return reader; 
    } 


    private LineMapper<User> createUserLineMapper() { 
     DefaultLineMapper<User> userLineMapper = new DefaultLineMapper<>(); 
     LineTokenizer userLineTokenizer = createUserLineTokenizer(); 
     userLineMapper.setLineTokenizer(userLineTokenizer); 
     FieldSetMapper<User> userInformationMapper = createUserInformationMapper(); 
     userLineMapper.setFieldSetMapper(userInformationMapper); 
     return userLineMapper; 
    } 


    private LineTokenizer createUserLineTokenizer() { 
     DelimitedLineTokenizer userLineTokenizer = new DelimitedLineTokenizer(); 
     userLineTokenizer.setDelimiter(environment.getProperty("column.delimiter")); 
     userLineTokenizer.setNames(environment.getProperty("column.names").split(",")); 
     return userLineTokenizer; 
    } 

    private FieldSetMapper<User> createUserInformationMapper() { 
     BeanWrapperFieldSetMapper<User> userInformationMapper = new BeanWrapperFieldSetMapper<>(); 
     userInformationMapper.setTargetType(User.class); 
     return userInformationMapper; 
    } 

    @Bean 
    public UserItemProcessor processor(){ 
     return new UserItemProcessor(); 
    } 

    @Bean 
    public JdbcBatchItemWriter<User> writer(){ 
     JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>(); 
     writer.setDataSource(dataSource); 
     writer.setSql("INSERT INTO user (name, id) VALUES (?,?)"); 
     writer.setItemPreparedStatementSetter(new UserItemPreparedStatementSetter()); 
     return writer; 
    } 

    @Bean 
    public Step step1(){ 
     return stepBuilderFactory.get("step1") 
       .<User, User> chunk(10000) 
       .reader(reader()) 
       .faultTolerant() 
       .skipPolicy(fileVerificationSkipper()) 
       .processor(processor()) 
       .writer(writer()) 
       .build(); 
    } 


    @Bean 
    public Job importUserJob(){ 
     return jobBuilderFactory.get("importUserJob") 
       .incrementer(new RunIdIncrementer()) 
       .flow(step1()) 
       .end() 
       .build(); 
    } 

    @Bean 
    public SkipPolicy fileVerificationSkipper() { 
     return new FileVerificationSkipper(); 
    } 

    /*@Bean 
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    }*/ 

} 

和我HibernateUtil.java是:如何將Spring Boot與Hibernate集成?

package com.batch.hibernate.util; 

import java.util.Properties; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.service.ServiceRegistry; 

import com.batch.hibernate.model.User; 

public class HibernateUtil { 

    private static final SessionFactory sessionFactory = buildSessionFactory(); 

    private static SpringBatchUtil springBatchUtil; 

    private static Properties properties; 

    public static SessionFactory buildSessionFactory() { 
     SessionFactory localSessionFactory = null; 
     springBatchUtil = new SpringBatchUtil(); 
     try { 
      Configuration configuration = new Configuration(); 
      properties = springBatchUtil.loadProperties(); 

      configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_URL, 
        properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_URL)); 
      configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_USERNAME, 
        properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_USERNAME)); 
      configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_PASSWORD, 
        properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_PASSWORD)); 

      configuration.setProperty(SpringBatchConstants.HIBERNATE_SHOW_SQL, 
        properties.getProperty(SpringBatchConstants.HIBERNATE_SHOW_SQL)); 
      configuration.setProperty(SpringBatchConstants.HIBERNATE_CURRENT_SESSION_CONTEXT_CLASS, 
        properties.getProperty(SpringBatchConstants.HIBERNATE_CURRENT_SESSION_CONTEXT_CLASS)); 
      configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_DRIVER_CLASS, 
        properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_DRIVER_CLASS)); 

      configuration.addPackage("com.batch.hibernate.model"); 
      configuration.addAnnotatedClass(User.class); 

      ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() 
        .applySettings(configuration.getProperties()).build(); 

      localSessionFactory = configuration.buildSessionFactory(serviceRegistry); 
     } catch (HibernateException he) { 
      he.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return localSessionFactory; 
    } 

    public static SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public static Session getSession() throws Exception { 
     if (getSessionFactory() == null) { 
      throw new HibernateException("Initial SessionFactory creation failed."); 
     } 
     Session session = getSessionFactory().getCurrentSession(); 
     session.getTransaction().begin(); 
     return session; 

    } 

    public static void closeSession(Session session) { 
     if (session != null) { 
      if (session.getTransaction().isActive()) { 
       session.getTransaction().commit(); 
      } 
      session.close(); 
     } 
    } 

} 

我有數據源設置和的HibernateUtil如上,我希望使用Hibernate而不是JDBC在配置數據源。 與hibernate集成的主要原因是審計目的,同時從文件到數據庫寫入記錄。

如何在這裏使用hibernate?或者有沒有辦法使用我已經使用的方式進行審計?

對不起,如果我不清楚我的問題。

回答

0

看看Spring-starter-data-jpa。設置所需的屬性,如hibernate.dialect等,你不需要自己做任何事情,它的作品o.o.t.b.