View Javadoc

1   /*
2    * Copyright 2006-2013 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.batch.sample.domain.trade.internal;
18  
19  import java.util.List;
20  
21  import org.hibernate.SessionFactory;
22  import org.springframework.batch.item.ItemWriter;
23  import org.springframework.batch.sample.domain.trade.CustomerCredit;
24  import org.springframework.batch.sample.domain.trade.CustomerCreditDao;
25  import org.springframework.beans.factory.InitializingBean;
26  import org.springframework.util.Assert;
27  
28  /**
29   * Delegates writing to a custom DAO and flushes + clears hibernate session to
30   * fulfill the {@link ItemWriter} contract.
31   *
32   * @author Robert Kasanicky
33   * @author Michael Minella
34   */
35  public class HibernateAwareCustomerCreditItemWriter implements ItemWriter<CustomerCredit>, InitializingBean {
36  
37  	private CustomerCreditDao dao;
38  
39  	private SessionFactory sessionFactory;
40  
41  	public void write(List<? extends CustomerCredit> items) throws Exception {
42  		for (CustomerCredit credit : items) {
43  			dao.writeCredit(credit);
44  		}
45  		try {
46  			sessionFactory.getCurrentSession().flush();
47  		}
48  		finally {
49  			// this should happen automatically on commit, but to be on the safe
50  			// side...
51  			sessionFactory.getCurrentSession().clear();
52  		}
53  
54  	}
55  
56  	public void setDao(CustomerCreditDao dao) {
57  		this.dao = dao;
58  	}
59  
60  	public void setSessionFactory(SessionFactory sessionFactory) {
61  		this.sessionFactory = sessionFactory;
62  	}
63  
64  	public void afterPropertiesSet() throws Exception {
65  		Assert.state(sessionFactory != null, "Hibernate SessionFactory is required");
66  		Assert.notNull(dao, "Delegate DAO must be set");
67  	}
68  
69  }