Search in sources :

Example 31 with PersistenceException

use of javax.persistence.PersistenceException in project ORCID-Source by ORCID.

the class ResearcherUrlDaoTest method testCannotAddDuplicatedResearcherUrl.

@Test
@Rollback(true)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testCannotAddDuplicatedResearcherUrl() {
    try {
        ResearcherUrlEntity newRUrl = new ResearcherUrlEntity();
        newRUrl.setDateCreated(new Date());
        newRUrl.setLastModified(new Date());
        newRUrl.setClientSourceId("4444-4444-4444-4443");
        newRUrl.setUrl("http://www.researcherurl2.com?id=1");
        newRUrl.setUrlName("test");
        newRUrl.setUser(new ProfileEntity("4444-4444-4444-4443"));
        newRUrl.setVisibility(Visibility.PUBLIC);
        newRUrl = dao.merge(newRUrl);
        assertNotNull(newRUrl);
        fail();
    } catch (PersistenceException e) {
    }
}
Also used : ResearcherUrlEntity(org.orcid.persistence.jpa.entities.ResearcherUrlEntity) PersistenceException(javax.persistence.PersistenceException) Date(java.util.Date) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Test(org.junit.Test) DBUnitTest(org.orcid.test.DBUnitTest) Rollback(org.springframework.test.annotation.Rollback) Transactional(org.springframework.transaction.annotation.Transactional)

Example 32 with PersistenceException

use of javax.persistence.PersistenceException in project learn-hanzi by reinardhz.

the class HanziServiceImpl method insertHanzi.

/**
 * A method to insert inputted hanzi to database.
 *
 * If the data successfully inserted to database , return the successfull inserted hanzi and its created date in json format.
 * Response json string example: {"hanzi_data":[{"hanzi":"會", "created_date":"1491448282654"}]}. <br/>
 *
 * <br/>
 *
 * @param hanzi - String hanzi to insert.
 * @return String result - The inserted hanzi data in json format, or String: "Error: Cannot insert. Data already exist.", if trying to insert the already inserted data.
 * @throws Exception - If errors occurs when inserting data to database.
 */
public String insertHanzi(String input) throws Exception {
    try {
        logger.info("Inserting hanzi to database...");
        logger.debug("preparing the data...");
        HanziData inputHanziData = new HanziData();
        inputHanziData.setHanzi(input);
        inputHanziData.setCreated_date(System.currentTimeMillis());
        logger.debug("preparing the child...");
        Set<UserAndHanzi> childs = new HashSet<UserAndHanzi>();
        UserAndHanzi child = new UserAndHanzi();
        UserData userData = new UserData();
        // manual input
        userData.setUser_id(1L);
        child.setUserData(userData);
        child.setHanziData(inputHanziData);
        childs.add(child);
        // add the child
        logger.debug("adding the child to the data...");
        inputHanziData.setUserAndHanzi(childs);
        logger.debug("call dao, to insert data to database");
        HanziData insertedHanziData = hanziDaoImpl.insert(inputHanziData);
        logger.info("Insert hanzi to database succeed");
        logger.info("Converting the inserted data to json object...");
        logger.debug("Preparing the json object...");
        HanziDataJsonResponseObject resultJsonObject = new HanziDataJsonResponseObject();
        logger.debug("Preparing the child json object...");
        Hanzi_data resultChildJsonObject = new Hanzi_data();
        resultChildJsonObject.setHanzi(insertedHanziData.getHanzi());
        resultChildJsonObject.setCreated_date(String.valueOf(insertedHanziData.getCreated_date()));
        logger.debug("Converting the child json object into array...");
        List<Hanzi_data> var = new ArrayList<>();
        var.add(resultChildJsonObject);
        Hanzi_data[] resultChildJsonArray = var.<Hanzi_data>toArray(new Hanzi_data[0]);
        logger.debug("Adding the array into json object...");
        resultJsonObject.setHanzi_data(resultChildJsonArray);
        logger.debug("Converting json object into json string...");
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(resultJsonObject);
        return result;
    } catch (PersistenceException pe) {
        logger.error("Cannot insert. Data already exist.");
        return "Error: Cannot insert. Data already exist.";
    } catch (Exception e) {
        logger.error("Unexpected error occurred when inserting hanzi to database.");
        throw e;
    }
}
Also used : Hanzi_data(com.reinard.learnhanzi.json.Hanzi_data) HanziDataJsonResponseObject(com.reinard.learnhanzi.json.HanziDataJsonResponseObject) UserData(com.reinard.learnhanzi.models.UserData) ArrayList(java.util.ArrayList) PersistenceException(javax.persistence.PersistenceException) UserAndHanzi(com.reinard.learnhanzi.models.UserAndHanzi) PersistenceException(javax.persistence.PersistenceException) HanziData(com.reinard.learnhanzi.models.HanziData) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet)

Example 33 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class CallbackBuilderLegacyImpl method resolveCallbacks.

@SuppressWarnings({ "unchecked", "WeakerAccess" })
public Callback[] resolveCallbacks(XClass beanClass, CallbackType callbackType, ReflectionManager reflectionManager) {
    List<Callback> callbacks = new ArrayList<>();
    List<String> callbacksMethodNames = new ArrayList<>();
    List<Class> orderedListeners = new ArrayList<>();
    XClass currentClazz = beanClass;
    boolean stopListeners = false;
    boolean stopDefaultListeners = false;
    do {
        Callback callback = null;
        List<XMethod> methods = currentClazz.getDeclaredMethods();
        for (final XMethod xMethod : methods) {
            if (xMethod.isAnnotationPresent(callbackType.getCallbackAnnotation())) {
                Method method = reflectionManager.toMethod(xMethod);
                final String methodName = method.getName();
                if (!callbacksMethodNames.contains(methodName)) {
                    // overridden method, remove the superclass overridden method
                    if (callback == null) {
                        callback = new EntityCallback(method, callbackType);
                        Class returnType = method.getReturnType();
                        Class[] args = method.getParameterTypes();
                        if (returnType != Void.TYPE || args.length != 0) {
                            throw new RuntimeException("Callback methods annotated on the bean class must return void and take no arguments: " + callbackType.getCallbackAnnotation().getName() + " - " + xMethod);
                        }
                        ReflectHelper.ensureAccessibility(method);
                        log.debugf("Adding %s as %s callback for entity %s", methodName, callbackType.getCallbackAnnotation().getSimpleName(), beanClass.getName());
                        // superclass first
                        callbacks.add(0, callback);
                        callbacksMethodNames.add(0, methodName);
                    } else {
                        throw new PersistenceException("You can only annotate one callback method with " + callbackType.getCallbackAnnotation().getName() + " in bean class: " + beanClass.getName());
                    }
                }
            }
        }
        if (!stopListeners) {
            getListeners(currentClazz, orderedListeners);
            stopListeners = currentClazz.isAnnotationPresent(ExcludeSuperclassListeners.class);
            stopDefaultListeners = currentClazz.isAnnotationPresent(ExcludeDefaultListeners.class);
        }
        do {
            currentClazz = currentClazz.getSuperclass();
        } while (currentClazz != null && !(currentClazz.isAnnotationPresent(Entity.class) || currentClazz.isAnnotationPresent(MappedSuperclass.class)));
    } while (currentClazz != null);
    // handle default listeners
    if (!stopDefaultListeners) {
        List<Class> defaultListeners = (List<Class>) reflectionManager.getDefaults().get(EntityListeners.class);
        if (defaultListeners != null) {
            int defaultListenerSize = defaultListeners.size();
            for (int i = defaultListenerSize - 1; i >= 0; i--) {
                orderedListeners.add(defaultListeners.get(i));
            }
        }
    }
    for (Class listener : orderedListeners) {
        Callback callback = null;
        if (listener != null) {
            XClass xListener = reflectionManager.toXClass(listener);
            callbacksMethodNames = new ArrayList<>();
            List<XMethod> methods = xListener.getDeclaredMethods();
            for (final XMethod xMethod : methods) {
                if (xMethod.isAnnotationPresent(callbackType.getCallbackAnnotation())) {
                    final Method method = reflectionManager.toMethod(xMethod);
                    final String methodName = method.getName();
                    if (!callbacksMethodNames.contains(methodName)) {
                        // overridden method, remove the superclass overridden method
                        if (callback == null) {
                            callback = new ListenerCallback(managedBeanRegistry.getBean(listener), method, callbackType);
                            Class returnType = method.getReturnType();
                            Class[] args = method.getParameterTypes();
                            if (returnType != Void.TYPE || args.length != 1) {
                                throw new PersistenceException("Callback methods annotated in a listener bean class must return void and take one argument: " + callbackType.getCallbackAnnotation().getName() + " - " + method);
                            }
                            ReflectHelper.ensureAccessibility(method);
                            log.debugf("Adding %s as %s callback for entity %s", methodName, callbackType.getCallbackAnnotation().getSimpleName(), beanClass.getName());
                            // listeners first
                            callbacks.add(0, callback);
                        } else {
                            throw new PersistenceException("You can only annotate one callback method with " + callbackType.getCallbackAnnotation().getName() + " in bean class: " + beanClass.getName() + " and callback listener: " + listener.getName());
                        }
                    }
                }
            }
        }
    }
    return callbacks.toArray(new Callback[callbacks.size()]);
}
Also used : ArrayList(java.util.ArrayList) XMethod(org.hibernate.annotations.common.reflection.XMethod) Method(java.lang.reflect.Method) XClass(org.hibernate.annotations.common.reflection.XClass) EntityListeners(javax.persistence.EntityListeners) Callback(org.hibernate.jpa.event.spi.Callback) XMethod(org.hibernate.annotations.common.reflection.XMethod) ExcludeDefaultListeners(javax.persistence.ExcludeDefaultListeners) PersistenceException(javax.persistence.PersistenceException) XClass(org.hibernate.annotations.common.reflection.XClass) ArrayList(java.util.ArrayList) List(java.util.List) ExcludeSuperclassListeners(javax.persistence.ExcludeSuperclassListeners)

Example 34 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class EntityManagerTest method testPersistExisting.

@Test
public void testPersistExisting() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Wallet w = new Wallet();
    w.setBrand("Lacoste");
    w.setModel("Minimic");
    w.setSerial("0100202002");
    em.persist(w);
    w = new Wallet();
    w.setBrand("Lacoste");
    w.setModel("Minimic");
    w.setSerial("0100202002");
    try {
        em.persist(w);
    } catch (EntityExistsException eee) {
        // success
        if (em.getTransaction() != null) {
            em.getTransaction().rollback();
        }
        em.close();
        return;
    }
    try {
        em.getTransaction().commit();
        fail("Should have raised an exception");
    } catch (PersistenceException pe) {
    } finally {
        em.close();
    }
}
Also used : EntityManager(javax.persistence.EntityManager) PersistenceException(javax.persistence.PersistenceException) EntityExistsException(javax.persistence.EntityExistsException) Test(org.junit.Test)

Example 35 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class AttributeConverterSqlTypeDescriptorAdapter method getBinder.

// Binding ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
@SuppressWarnings("unchecked")
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
    // Get the binder for the intermediate type representation
    final ValueBinder realBinder = delegate.getBinder(intermediateJavaTypeDescriptor);
    return new ValueBinder<X>() {

        @Override
        public void bind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
            final Object convertedValue;
            try {
                convertedValue = converter.toRelationalValue(value);
            } catch (PersistenceException pe) {
                throw pe;
            } catch (RuntimeException re) {
                throw new PersistenceException("Error attempting to apply AttributeConverter", re);
            }
            log.debugf("Converted value on binding : %s -> %s", value, convertedValue);
            realBinder.bind(st, convertedValue, index, options);
        }

        @Override
        public void bind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
            final Object convertedValue;
            try {
                convertedValue = converter.toRelationalValue(value);
            } catch (PersistenceException pe) {
                throw pe;
            } catch (RuntimeException re) {
                throw new PersistenceException("Error attempting to apply AttributeConverter", re);
            }
            log.debugf("Converted value on binding : %s -> %s", value, convertedValue);
            realBinder.bind(st, convertedValue, name, options);
        }
    };
}
Also used : CallableStatement(java.sql.CallableStatement) WrapperOptions(org.hibernate.type.descriptor.WrapperOptions) PersistenceException(javax.persistence.PersistenceException) PreparedStatement(java.sql.PreparedStatement) ValueBinder(org.hibernate.type.descriptor.ValueBinder)

Aggregations

PersistenceException (javax.persistence.PersistenceException)191 Test (org.junit.Test)73 Session (org.hibernate.Session)57 EntityManager (javax.persistence.EntityManager)39 Transaction (org.hibernate.Transaction)34 EntityTransaction (javax.persistence.EntityTransaction)21 IOException (java.io.IOException)18 Query (javax.persistence.Query)18 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)18 List (java.util.List)16 ArrayList (java.util.ArrayList)14 TypedQuery (javax.persistence.TypedQuery)11 JPAQuery (org.datanucleus.api.jpa.JPAQuery)10 StaleObjectStateException (org.hibernate.StaleObjectStateException)10 SQLGrammarException (org.hibernate.exception.SQLGrammarException)8 HashMap (java.util.HashMap)6 Iterator (java.util.Iterator)6 Person (org.datanucleus.samples.annotations.models.company.Person)6 MessagesEvent (com.openmeap.event.MessagesEvent)5 SQLException (java.sql.SQLException)5