001/* 002 * Copyright 2006-2013 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 */ 016 017package org.springframework.batch.sample.domain.trade.internal; 018 019import java.util.List; 020 021import org.hibernate.SessionFactory; 022import org.springframework.batch.item.ItemWriter; 023import org.springframework.batch.sample.domain.trade.CustomerCredit; 024import org.springframework.batch.sample.domain.trade.CustomerCreditDao; 025import org.springframework.beans.factory.InitializingBean; 026import org.springframework.util.Assert; 027 028/** 029 * Delegates writing to a custom DAO and flushes + clears hibernate session to 030 * fulfill the {@link ItemWriter} contract. 031 * 032 * @author Robert Kasanicky 033 * @author Michael Minella 034 */ 035public class HibernateAwareCustomerCreditItemWriter implements ItemWriter<CustomerCredit>, InitializingBean { 036 037 private CustomerCreditDao dao; 038 039 private SessionFactory sessionFactory; 040 041 @Override 042 public void write(List<? extends CustomerCredit> items) throws Exception { 043 for (CustomerCredit credit : items) { 044 dao.writeCredit(credit); 045 } 046 try { 047 sessionFactory.getCurrentSession().flush(); 048 } 049 finally { 050 // this should happen automatically on commit, but to be on the safe 051 // side... 052 sessionFactory.getCurrentSession().clear(); 053 } 054 055 } 056 057 public void setDao(CustomerCreditDao dao) { 058 this.dao = dao; 059 } 060 061 public void setSessionFactory(SessionFactory sessionFactory) { 062 this.sessionFactory = sessionFactory; 063 } 064 065 @Override 066 public void afterPropertiesSet() throws Exception { 067 Assert.state(sessionFactory != null, "Hibernate SessionFactory is required"); 068 Assert.notNull(dao, "Delegate DAO must be set"); 069 } 070 071}