org.aktivecortex.core.store.command.JpaCommandStore Maven / Gradle / Ivy
/*
* Copyright (C) 2012-2013. Aktive Cortex
*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.aktivecortex.core.store.command;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.aktivecortex.api.command.Command;
import org.axonframework.eventstore.jpa.PersistenceExceptionResolver;
import org.axonframework.eventstore.jpa.SQLErrorCodesResolver;
import org.axonframework.repository.ConcurrencyException;
/**
* @author Domenico Maria Giffone
*
*/
public class JpaCommandStore implements CommandStore {
@PersistenceContext
private EntityManager entityManager;
private org.axonframework.serializer.Serializer commandSerializer;
private final CommandEntryStore commandEntryStore;
private PersistenceExceptionResolver persistenceExceptionResolver;
public void setDataSource(DataSource dataSource) throws SQLException {
this.persistenceExceptionResolver = new SQLErrorCodesResolver(dataSource);
}
public void setSerializer(org.axonframework.serializer.Serializer serializer) {
this.commandSerializer = serializer;
}
/**
*
*/
protected JpaCommandStore() {
commandEntryStore = new DefaultCommandEntryStore();
}
@Override
public void addCommand(Command command) {
try {
commandEntryStore.persistCommand(command, commandSerializer.serialize(command), entityManager);
} catch (RuntimeException e) {
if (persistenceExceptionResolver != null
&& persistenceExceptionResolver.isDuplicateKeyViolation(e)) {
throw new ConcurrencyException(
String.format("Concurrent execution detected of command [%s]",
command),
e);
}
throw e;
}
}
}