Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   * Copyright 2006-2008 the original author or authors.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
 package org.springframework.batch.item.database;
 import java.util.List;
org.springframework.batch.item.ItemWriter that is using a JPA EntityManagerFactory to merge any Entities that aren't part of the persistence context. It is required that write(java.util.List) is called inside a transaction.
The reader must be configured with an javax.persistence.EntityManagerFactory that is capable of participating in Spring managed transactions. The writer is thread safe after its properties are set (normal singleton behaviour), so it can be used to write in multiple concurrent transactions.

Thomas Risberg
 public class JpaItemWriter<T> implements ItemWriter<T>, InitializingBean {
 	protected static final Log logger = LogFactory.getLog(JpaItemWriter.class);
Set the EntityManager to be used internally.

entityManagerFactory the entityManagerFactory to set
 	public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
 		this. = entityManagerFactory;

Check mandatory properties - there must be an entityManagerFactory.
 	public void afterPropertiesSet() throws Exception {
 		Assert.notNull("An EntityManagerFactory is required");

Merge all provided items that aren't already in the persistence context and then flush and clear the entity manager.

 	public final void write(List<? extends T> items) {
 		EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager();
 		if (entityManager == null) {
 			throw new DataAccessResourceFailureException("Unable to obtain a transactional EntityManager");
 		try {
 		finally {

Do perform the actual write operation. This can be overridden in a subclass if necessary.

entityManager the EntityManager to use for the operation
items the list of items to use for the write
 	protected void doWrite(EntityManager entityManagerList<? extends T> items) {
 		if (.isDebugEnabled()) {
			.debug("Writing to JPA with " + items.size() + " items.");
		if (!items.isEmpty()) {
			long mergeCount = 0;
			for (T item : items) {
				if (!entityManager.contains(item)) {
				.debug(mergeCount + " entities merged.");
				.debug((items.size() - mergeCount) + " entities found in persistence context.");
New to GrepCode? Check out our FAQ X