org.eclipse.persistence.jpa.JpaEntityManager Java Examples

The following examples show how to use org.eclipse.persistence.jpa.JpaEntityManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KradEclipseLinkEntityManagerFactoryBeanTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Just tests some of the getters to ensure they are delegating down to the internal factory bean and the
 * PersistenceUnitManager appropriately.
 */
@Test
public void testVariousGetters() throws Exception {
    loadContext(getClass().getSimpleName() +  "_LoadTimeWeaving.xml");
    KradEclipseLinkEntityManagerFactoryBean factoryBean =
            context.getBean(KradEclipseLinkEntityManagerFactoryBean.class);
    assertNotNull(factoryBean);

    assertEquals(2, factoryBean.getPersistenceUnitPostProcessors().length);
    EntityManagerFactory entityManagerFactory = factoryBean.getNativeEntityManagerFactory();
    assertTrue(entityManagerFactory instanceof EntityManagerFactoryImpl);
    assertEquals(factoryBean.getBeanClassLoader(), getClass().getClassLoader());
    assertEquals(JpaEntityManager.class, factoryBean.getEntityManagerInterface());

}
 
Example #2
Source File: JpaPersistenceProvider.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
   @Transactional
public <T> T copyInstance(final T dataObject, CopyOption... options) {
	final CopyGroup copyGroup = new CopyGroup();
	if (ArrayUtils.contains(options, CopyOption.RESET_PK_FIELDS)) {
		copyGroup.setShouldResetPrimaryKey(true);
	}
	final boolean shouldResetVersionNumber = ArrayUtils.contains(options, CopyOption.RESET_VERSION_NUMBER);
	if (shouldResetVersionNumber) {
		copyGroup.setShouldResetVersion(true);
	}
	final boolean shouldResetObjectId = ArrayUtils.contains(options, CopyOption.RESET_OBJECT_ID);
       return doWithExceptionTranslation(new Callable<T>() {
		@SuppressWarnings("unchecked")
		@Override
           public T call() {
			T copiedObject = (T) sharedEntityManager.unwrap(JpaEntityManager.class).getDatabaseSession()
					.copy(dataObject, copyGroup);
			if (shouldResetObjectId) {
				clearObjectIdOnUpdatableObjects(copiedObject, new HashSet<Object>());
			}
			if (shouldResetVersionNumber) {
			    clearVersionNumberOnUpdatableObjects(copiedObject, new HashSet<Object>());
			}
			return copiedObject;
           }
       });
   }
 
Example #3
Source File: DatabaseNetwork.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return all active vertices.
 */
@SuppressWarnings("unchecked")
public synchronized List<Vertex> allActive() {
	UnitOfWork unitOfWork = this.entityManager.unwrap(JpaEntityManager.class).getUnitOfWork();
	try {
		return unitOfWork.getIdentityMapAccessor().getAllFromIdentityMap(null, BasicVertex.class, null, null);
	} catch (Exception exception) {
		return new ArrayList<Vertex>();
	}
}
 
Example #4
Source File: JPQL2SQLStatementRewriter.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String rewrite(String query) {
	if (this.entityManager instanceof org.eclipse.persistence.jpa.JpaEntityManager) {
		return rewriteEclipseLink(query);
	} else {
		return rewriteHibernate(query);
	}
}
 
Example #5
Source File: JPQL2SQLStatementRewriter.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String rewrite(Query query) {
	if (this.entityManager instanceof org.eclipse.persistence.jpa.JpaEntityManager) {
		return rewriteEclipseLink(query);
	} else {
		return rewriteHibernate(query);
	}
}
 
Example #6
Source File: JPQL2SQLStatementRewriter.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Rewrite the JPQL query in a SQL String (The persistence provider implementation in use is EclipseLink)
 * 
 * @param query
 *            The JPQL query
 * @return the string of the JPQL query translated in SQL
 */
private String rewriteEclipseLink(Query query) {
	EJBQueryImpl qi = (EJBQueryImpl) query;
	Session session = this.entityManager.unwrap(JpaEntityManager.class).getActiveSession();
	DatabaseQuery databaseQuery = (qi).getDatabaseQuery();
	databaseQuery.prepareCall(session, new DatabaseRecord());
	String sqlString = databaseQuery.getTranslatedSQLString(session, new DatabaseRecord());

	// ADD THE ALIAS in the select statement (necessary for the temporary table construction..)
	int fromPosition = sqlString.indexOf("FROM");
	StringBuffer sqlQuery2 = new StringBuffer();
	String SelectStatement = sqlString.substring(0, fromPosition - 1);
	StringTokenizer SelectStatementStk = new StringTokenizer(SelectStatement, ",");
	int i = 0;
	while (SelectStatementStk.hasMoreTokens()) {
		sqlQuery2.append(SelectStatementStk.nextToken());
		sqlQuery2.append(" as alias");
		sqlQuery2.append(i);
		sqlQuery2.append(",");
		i++;
	}
	sqlQuery2.delete(sqlQuery2.length() - 1, sqlQuery2.length());
	sqlQuery2.append(sqlString.substring(fromPosition - 1));

	logger.debug("JPQL QUERY: " + sqlQuery2);

	return sqlQuery2.toString();
}
 
Example #7
Source File: SoftDeleteTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected boolean setPrintInnerJoinInWhereClause(EntityManager entityManager, boolean value) {
    JpaEntityManager jpaEntityManager = (JpaEntityManager) entityManager.getDelegate();
    DatabasePlatform platform = jpaEntityManager.getActiveSession().getPlatform();
    boolean prevValue = platform.shouldPrintInnerJoinInWhereClause();
    platform.setPrintInnerJoinInWhereClause(value);
    return prevValue;
}
 
Example #8
Source File: EclipseLinkJpaVendorAdapter.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Class<? extends EntityManager> getEntityManagerInterface() {
	return JpaEntityManager.class;
}
 
Example #9
Source File: QuestionServiceImpl.java    From gazpachoquest with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Transactional
public List<Question> findInList(List<Integer> questionIds, Language language) {
    if (questionIds.isEmpty()) {
        return Collections.emptyList();
    }
    List<Question> questions = ((QuestionRepository) repository).findInList(questionIds);
    if (questions.isEmpty()) {
        return Collections.emptyList();
    }

    Question sampleQuestion = questions.iterator().next();
    // It's assumed that all the question are in the same language
    boolean isPreferredLanguage = language == null || sampleQuestion.getLanguage().equals(language);

    CopyGroup group = new CopyGroup();

    group.addAttribute("questionOptions");
    group.addAttribute("languageSettings");
    group.addAttribute("language");
    group.addAttribute("type");
    group.addAttribute("code");
    group.addAttribute("relevance");

    group.addAttribute("subquestions.subquestions");
    group.addAttribute("subquestions.questionOptions");
    group.addAttribute("subquestions.language");
    group.addAttribute("subquestions.type");
    group.addAttribute("subquestions.code");
    group.addAttribute("subquestions.languageSettings");

    group.addAttribute("questionOptions.languageSettings");
    group.addAttribute("questionOptions.language");
    group.addAttribute("questionOptions.code");
    // Only load translations is question language is different from
    // preferred
    // language
    if (!isPreferredLanguage) {
        group.addAttribute("translations");
        group.addAttribute("subquestions.translations");
        group.addAttribute("questionOptions.translations");
    }

    List<Question> detatchedQuestions = new ArrayList<>();
    for (Question question : questions) {
        Question detatchedQuestion = (Question) entityManager.unwrap(JpaEntityManager.class).copy(question, group);
        if (!isPreferredLanguage) {
            detatchedQuestion.translateTo(language);
        }
        detatchedQuestions.add(detatchedQuestion);
    }
    return sortQuestions(detatchedQuestions, questionIds);
}
 
Example #10
Source File: CubaEclipseLinkJpaDialect.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
    Object result = super.beginTransaction(entityManager, definition);
    Preconditions.checkState(result == null, "Transactional data should be null for EclipseLink dialect");

    // Read default timeout every time - may be somebody wants to change it on the fly
    int defaultTimeout = 0;
    String defaultTimeoutProp = AppContext.getProperty("cuba.defaultQueryTimeoutSec");
    if (!"0".equals(defaultTimeoutProp) && !StringUtils.isBlank(defaultTimeoutProp)) {
        try {
            defaultTimeout = Integer.parseInt(defaultTimeoutProp);
        } catch (NumberFormatException e) {
            log.error("Invalid cuba.defaultQueryTimeoutSec value", e);
        }
    }

    int timeoutSec = 0;
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT)
        timeoutSec = definition.getTimeout();
    else if (defaultTimeout != 0)
        timeoutSec = defaultTimeout;

    if (timeoutSec != 0) {
        log.trace("Applying query timeout {} sec", timeoutSec);
        if (entityManager instanceof JpaEntityManager) {
            UnitOfWork unitOfWork = ((JpaEntityManager) entityManager).getUnitOfWork();
            if (unitOfWork != null) {
                //setup delay in seconds on unit of work
                unitOfWork.setQueryTimeoutDefault(timeoutSec);
            }
        }

        String s = DbmsSpecificFactory.getDbmsFeatures().getTransactionTimeoutStatement();
        if (s != null) {
            Connection connection = entityManager.unwrap(Connection.class);
            try (Statement statement = connection.createStatement()) {
                statement.execute(String.format(s, timeoutSec * 1000));
            }
        }
    }

    return new CubaEclipseLinkTransactionData(entityManager);
}
 
Example #11
Source File: EclipseLinkEntityManagerFactoryIntegrationTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public void testCanCastSharedEntityManagerProxyToEclipseLinkEntityManager() {
	assertTrue(sharedEntityManager instanceof JpaEntityManager);
	JpaEntityManager eclipselinkEntityManager = (JpaEntityManager) sharedEntityManager;
	assertNotNull(eclipselinkEntityManager.getActiveSession());
}
 
Example #12
Source File: EclipseLinkJpaVendorAdapter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Class<? extends EntityManager> getEntityManagerInterface() {
	return JpaEntityManager.class;
}
 
Example #13
Source File: EclipseLinkJpaVendorAdapter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Class<? extends EntityManager> getEntityManagerInterface() {
	return JpaEntityManager.class;
}
 
Example #14
Source File: EclipseLinkEntityManagerFactoryIntegrationTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void testCanCastSharedEntityManagerProxyToEclipseLinkEntityManager() {
	assertTrue(sharedEntityManager instanceof JpaEntityManager);
	JpaEntityManager eclipselinkEntityManager = (JpaEntityManager) sharedEntityManager;
	assertNotNull(eclipselinkEntityManager.getActiveSession());
}
 
Example #15
Source File: EclipseLinkJpaVendorAdapter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Class<? extends EntityManager> getEntityManagerInterface() {
	return JpaEntityManager.class;
}
 
Example #16
Source File: EclipseLinkEntityManagerFactoryIntegrationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void testCanCastSharedEntityManagerProxyToEclipseLinkEntityManager() {
	assertTrue(sharedEntityManager instanceof JpaEntityManager);
	JpaEntityManager eclipselinkEntityManager = (JpaEntityManager) sharedEntityManager;
	assertNotNull(eclipselinkEntityManager.getActiveSession());
}
 
Example #17
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 2 votes vote down vote up
/**
    * The entity manager for interacting with the database.
    * @return the entity manager for interacting with the database.
    */
protected JpaEntityManager getEclipseLinkEntityManager() {
	return (JpaEntityManager) entityManager;
}