@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public T save(T entity) throws IllegalArgumentException, GeneralServiceException { if (entity == null) { throw new IllegalArgumentException("Entity for saving cannot be null!"); } T savedEntity = null; try { if (entity.getId() == null) { beforeEntityAddUpdate(entity); jpaTemplate.persist(entity); savedEntity = entity; } else { savedEntity = jpaTemplate.merge(entity); } } catch (Exception e) { if (entity.getId() == null) { throw new GeneralServiceException("Failed to add " + entity.getClass().getSimpleName(), e); } else { throw new GeneralServiceException( "Failed to update " + entity.getClass().getSimpleName() + " with id " + entity.getId(), e); } } return savedEntity; }
/** * Метод для выполнения запроса на поиск данных с выполнением всех необходимых операций, таких как * создание EntityManager, открытие транзакции, выполнение commit или roll back. * * <p>Метод задает параметры для запроса из списка начиная с 1. Первый параметр в запросе будет * <code>?1</code>, второй <code>?2</code> и т.д. * * <p>Если параметр <code>singleResult = true</code> и результатов не найдено, то будет возвращено * null. * * @param <REZ> Класс результата * @param queryOrQueryName строка запроса или название NamedQuery * @param namedQuery тип запроса (NamedQuery если true, обычный запрос если false) * @param singleResult возвращать один результат * @param parameters параметры через запятую (будут использоваться в запросе) * @return результат выполнения запроса * @throws IllegalArgumentException нет запроса */ @SuppressWarnings("unchecked") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) protected <REZ> REZ executeQuery( String queryOrQueryName, boolean namedQuery, boolean singleResult, Object... parameters) { if (null == queryOrQueryName || queryOrQueryName.isEmpty()) { throw new IllegalArgumentException("Query for executing cannot be empty"); } REZ result; List<?> list; if (namedQuery) { list = jpaTemplate.findByNamedQuery(queryOrQueryName, parameters); } else { list = jpaTemplate.find(queryOrQueryName, parameters); } if (singleResult) { if (!list.isEmpty()) { result = (REZ) list.get(0); } else { result = null; } } else { result = (REZ) list; } return result; }
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void delEntity(T entity) throws IllegalArgumentException, GeneralServiceException { if (entity == null) { throw new IllegalArgumentException("Entity must be not null!"); } if (entity.getId() == null) { return; } beforeEntityDelete(entity); try { if (!jpaTemplate.contains(entity)) { T attachedEntity = jpaTemplate.merge(entity); jpaTemplate.remove(attachedEntity); } else { jpaTemplate.remove(entity); } } catch (Exception e) { throw new GeneralServiceException( "Failed to delete " + entity.getClass().getSimpleName() + " with id " + entity.getId(), e); } }
@Test public void produceNewEntity() throws Exception { setUp("jpa://" + Customer.class.getName() + "?usePersist=" + (usePersist() ? "true" : "false")); Customer customer = createDefaultCustomer(); Exchange exchange = new DefaultExchange(camelContext); exchange.getIn().setBody(customer); Exchange returnedExchange = template.send(endpoint, exchange); Customer receivedCustomer = returnedExchange.getIn().getBody(Customer.class); assertEquals(customer.getName(), receivedCustomer.getName()); assertNotNull(receivedCustomer.getId()); assertEquals( customer.getAddress().getAddressLine1(), receivedCustomer.getAddress().getAddressLine1()); assertEquals( customer.getAddress().getAddressLine2(), receivedCustomer.getAddress().getAddressLine2()); assertNotNull(receivedCustomer.getAddress().getId()); List results = jpaTemplate.find("select o from " + Customer.class.getName() + " o"); assertEquals(1, results.size()); Customer persistedCustomer = (Customer) results.get(0); assertEquals(receivedCustomer.getName(), persistedCustomer.getName()); assertEquals(receivedCustomer.getId(), persistedCustomer.getId()); assertEquals( receivedCustomer.getAddress().getAddressLine1(), persistedCustomer.getAddress().getAddressLine1()); assertEquals( receivedCustomer.getAddress().getAddressLine2(), persistedCustomer.getAddress().getAddressLine2()); assertEquals(receivedCustomer.getAddress().getId(), persistedCustomer.getAddress().getId()); }
private void assertEntityInDB() throws Exception { jpaTemplate = (JpaTemplate) applicationContext.getBean("jpaTemplate", JpaTemplate.class); List list = jpaTemplate.find(SELECT_ALL_STRING); assertEquals(1, list.size()); assertIsInstanceOf(SendEmail.class, list.get(0)); }
public Personal loadPersonal(final Long actorId) { final StringBuffer hql = new StringBuffer("select p.id,p.uid_,p.status_,p.font,p.theme,p.aid,p.inner_"); hql.append(" from BC_DESKTOP_PERSONAL p where p.aid=0 or p.aid=? order by p.id desc"); if (logger.isDebugEnabled()) { logger.debug("actorId=" + actorId + ",hql=" + hql); } try { return jpaTemplate.execute( new JpaCallback<Personal>() { public Personal doInJpa(EntityManager em) throws PersistenceException { Query queryObject = em.createNativeQuery(hql.toString()); // jpaTemplate.prepareQuery(queryObject); // 注入参数 queryObject.setParameter(1, actorId); // jpa的索引号从1开始 queryObject.setFirstResult(0); queryObject.setMaxResults(1); // 仅获取1条 Personal p = new RowMapper<Personal>() { public Personal mapRow(Object[] rs, int rowNum) { Personal map = new Personal(); int i = 0; map.setId(new Long(rs[i++].toString())); map.setUid(rs[i] != null ? rs[i].toString() : null); i++; map.setStatus(Integer.parseInt(rs[i++].toString())); map.setFont(rs[i++].toString()); map.setTheme(rs[i++].toString()); map.setActorId(new Long(rs[i++].toString())); map.setInner("1".equals(rs[i++].toString())); return map; } }.mapRow((Object[]) queryObject.getSingleResult(), 0); // 如果是全局配置就将其改为当前用户的配置 if (p.getActorId().equals(0)) { p.setActorId(actorId); } return p; } }); } catch (NoResultException e) { return null; } }
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public T getEntityById(Long id) throws IllegalArgumentException { if (id == null) { throw new IllegalArgumentException("Id for finding entity should not be null"); } try { T savedEntity = jpaTemplate.find(persistentClass, id); if ((savedEntity == null) || (savedEntity.getId() == null)) { return null; } return (T) savedEntity; } catch (Exception e) { return null; } }
@SuppressWarnings("unchecked") protected void cleanupRepository() { jpaTemplate = (JpaTemplate) applicationContext.getBean("jpaTemplate", JpaTemplate.class); TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager( new JpaTransactionManager(jpaTemplate.getEntityManagerFactory())); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); transactionTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus arg0) { List list = jpaTemplate.find(SELECT_ALL_STRING); for (Object item : list) { jpaTemplate.remove(item); } jpaTemplate.flush(); return Boolean.TRUE; } }); }
/** * Метод для выполнения запроса на изменение данных (delete, update) с выполнением всех * необходимых операций, таких как создание EntityManager, открытие транзакции, выполнение commit * или roll back. * * <p>Метод задает параметры для запроса из списка начиная с 1. Первый параметр в запросе будет * <code>?1</code>, второй <code>?2</code> и т.д. * * @param queryOrQueryName строка запроса или название NamedQuery * @param namedQuery тип запроса (NamedQuery если true, обычный запрос если false) * @param parameters параметры через запятую (будут использоваться в запросе) * @return количество измененнных записей в базе * @throws IllegalArgumentException нет запроса * @throws GeneralServiceException */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) protected int executeUpdateQuery( final String queryOrQueryName, final boolean namedQuery, final Object... parameters) throws IllegalArgumentException, GeneralServiceException { if (null == queryOrQueryName || queryOrQueryName.isEmpty()) { throw new IllegalArgumentException("Query for executing cannot be empty"); } try { Object rez = jpaTemplate.execute( new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Query query; if (namedQuery) { query = em.createNamedQuery(queryOrQueryName); } else { query = em.createQuery(queryOrQueryName); } if (parameters.length > 0) { for (int i = 0; i < parameters.length; i++) { query.setParameter(i + 1, parameters[i]); } } return Integer.valueOf(query.executeUpdate()); } }); return ((Integer) rez).intValue(); } catch (Exception e) { throw new GeneralServiceException(e); } }
public Map<String, Object> loadActorByCode(final String actorCode) { final StringBuffer hql = new StringBuffer( "select a.id as id,a.uid_ as uid_,a.type_ as type_,a.code as code,a.name as name"); hql.append(",a.pcode as pcode,a.pname as pname,t.password as password,h.id as hid"); hql.append(" from bc_identity_actor as a"); hql.append(" inner join bc_identity_auth as t on t.id=a.id"); hql.append(" inner join bc_identity_actor_history as h on h.actor_id=a.id"); hql.append(" where a.code = ? and h.current='1' order by h.create_date desc"); if (logger.isDebugEnabled()) { logger.debug("actorCode=" + actorCode + ",hql=" + hql); } try { return jpaTemplate.execute( new JpaCallback<Map<String, Object>>() { public Map<String, Object> doInJpa(EntityManager em) throws PersistenceException { Query queryObject = em.createNativeQuery(hql.toString()); // jpaTemplate.prepareQuery(queryObject); // 注入参数 queryObject.setParameter(1, actorCode); // jpa的索引号从1开始 queryObject.setFirstResult(0); queryObject.setMaxResults(1); // 仅获取最新的那条(基于bc_identity_actor_history的create_date) return new RowMapper<Map<String, Object>>() { public Map<String, Object> mapRow(Object[] rs, int rowNum) { Map<String, Object> map = new HashMap<String, Object>(); int i = 0; // actor Actor actor = new Actor(); actor.setId(new Long(rs[i++].toString())); actor.setUid(rs[i++].toString()); actor.setType(Integer.parseInt(rs[i++].toString())); actor.setCode(rs[i++].toString()); actor.setName(rs[i++].toString()); actor.setPcode(rs[i++].toString()); actor.setPname(rs[i++].toString()); // auth AuthData auth = new AuthData(); auth.setId(actor.getId()); auth.setPassword(rs[i++].toString()); // history ActorHistory history = new ActorHistory(); history.setId(new Long(rs[i++].toString())); // history.setId(getActorHistoryId(actor.getId())); history.setActorId(actor.getId()); history.setActorType(actor.getType()); history.setName(actor.getName()); history.setPcode(actor.getPcode()); history.setPname(actor.getPname()); map.put("actor", actor); map.put("auth", auth); map.put("history", history); return map; } }.mapRow((Object[]) queryObject.getSingleResult(), 0); } }); } catch (EmptyResultDataAccessException e) { return new HashMap<String, Object>(0); } }
/** * Create a HibernateTemplate from the SessionFactory and call flush() and clear() on it. Designed * to be used after "save" methods in tests: http://issues.appfuse.org/browse/APF-178. */ protected void flush() { JpaTemplate jpaTemplate = new JpaTemplate((EntityManagerFactory) applicationContext.getBean("entityManagerFactory")); jpaTemplate.flush(); // jpaTemplate.clear(); }
protected void assertEntitiesInDatabase(int count, String entity) { List results = jpaTemplate.find("select o from " + entity + " o"); assertEquals(count, results.size()); }