001/* 002 * Copyright 2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.springframework.batch.item.database.builder; 017 018import org.hibernate.SessionFactory; 019 020import org.springframework.batch.item.database.HibernateItemWriter; 021import org.springframework.util.Assert; 022 023/** 024 * A builder for the {@link HibernateItemWriter} 025 * 026 * @author Michael Minella 027 * @since 4.0 028 * @see HibernateItemWriter 029 */ 030public class HibernateItemWriterBuilder<T> { 031 032 private boolean clearSession = true; 033 034 private SessionFactory sessionFactory; 035 036 /** 037 * If set to false, the {@link org.hibernate.Session} will not be cleared at the end 038 * of the chunk. 039 * 040 * @param clearSession defaults to true 041 * @return this instance for method chaining 042 * @see HibernateItemWriter#setClearSession(boolean) 043 */ 044 public HibernateItemWriterBuilder<T> clearSession(boolean clearSession) { 045 this.clearSession = clearSession; 046 047 return this; 048 } 049 050 /** 051 * The Hibernate {@link SessionFactory} to obtain a session from. Required. 052 * 053 * @param sessionFactory the {@link SessionFactory} 054 * @return this instance for method chaining 055 * @see HibernateItemWriter#setSessionFactory(SessionFactory) 056 */ 057 public HibernateItemWriterBuilder<T> sessionFactory(SessionFactory sessionFactory) { 058 this.sessionFactory = sessionFactory; 059 060 return this; 061 } 062 063 /** 064 * Returns a fully built {@link HibernateItemWriter} 065 * 066 * @return the writer 067 */ 068 public HibernateItemWriter<T> build() { 069 Assert.state(this.sessionFactory != null, 070 "SessionFactory must be provided"); 071 072 HibernateItemWriter<T> writer = new HibernateItemWriter<>(); 073 writer.setSessionFactory(this.sessionFactory); 074 writer.setClearSession(this.clearSession); 075 076 return writer; 077 } 078}