如何将Spring Boot与Hibernate集成?

时间:2017-06-18 05:14:24

标签: java database hibernate spring-batch datasource

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是:

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();
        }
    }

}

我有如上所述的dataSource设置和hibernateUtil,我想在配置dataSource时使用hibernate而不是JDBC。 与hibernate集成的主要原因是在将记录从文件写入数据库时​​进行审计。

如何在此上下文中使用hibernate?或者有没有办法使用我已经使用的方式进行审核?

很抱歉,如果我不清楚我的问题。

2 个答案:

答案 0 :(得分:0)

看看Spring-starter-data-jpa。设置所需的属性,如hibernate.dialect等,你不需要自己做任何事情,它的工作原理是o.o.t.b。

答案 1 :(得分:0)

Spring数据jpa应足以解决您的所有问题。

请查看此Repo的入门指南。

https://github.com/rahulrsingh09/Spring-Boot-DataJPA