当前位置: 首页>>代码示例>>Java>>正文


Java EntityManager.createQuery方法代码示例

本文整理汇总了Java中javax.persistence.EntityManager.createQuery方法的典型用法代码示例。如果您正苦于以下问题:Java EntityManager.createQuery方法的具体用法?Java EntityManager.createQuery怎么用?Java EntityManager.createQuery使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.persistence.EntityManager的用法示例。


在下文中一共展示了EntityManager.createQuery方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public static void main(String[] args) {
	EntityManagerFactory entityManagerFactory = Persistence
			.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();

	em.getTransaction().begin();
	
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<User> cq = cb.createQuery(User.class);
	Root<User> from = cq.from(User.class);
	Join<User, Role> join = from.join("role", JoinType.LEFT);
	cq.where(cb.equal(join.get("name"), "ordinary"));
	TypedQuery<User> tq = em.createQuery(cq);
	List<User> users = tq.getResultList();
	for (User u : users) {
		System.out.println(u.getLastName());
	}
	
	em.getTransaction().commit();
	em.close();
	entityManagerFactory.close();
}
 
开发者ID:PawelBogdan,项目名称:BecomeJavaHero,代码行数:23,代码来源:App8.java

示例2: executeJpqlQuery

import javax.persistence.EntityManager; //导入方法依赖的package包/类
/**
 * @return the number of entities updated or deleted
 */
public int executeJpqlQuery(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query query = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(query::setParameter);
        }
        em.getTransaction().begin();
        final int updatedOrDeleted = query.executeUpdate();
        em.getTransaction().commit();
        return updatedOrDeleted;
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to execute JPQL query %s with %s parameters on DB %s",
                queryString, parameters != null ? parameters.size() : "null", this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
开发者ID:napstr,项目名称:SqlSauce,代码行数:24,代码来源:DatabaseWrapper.java

示例3: selectJpqlQuerySingleResult

import javax.persistence.EntityManager; //导入方法依赖的package包/类
/**
 * Use this for COUNT() and similar jpql queries which are guaranteed to return a result
 */
@Nonnull
@CheckReturnValue
public <T> T selectJpqlQuerySingleResult(@Nonnull final String queryString,
                                         @Nullable final Map<String, Object> parameters,
                                         @Nonnull final Class<T> resultClass) throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        em.getTransaction().begin();
        final T result = resultClass.cast(q.getSingleResult());
        em.getTransaction().commit();
        return setSauce(result);
    } catch (final PersistenceException | ClassCastException e) {
        final String message = String.format("Failed to select single result JPQL query %s with %s parameters for class %s on DB %s",
                queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
开发者ID:napstr,项目名称:SqlSauce,代码行数:27,代码来源:DatabaseWrapper.java

示例4: getProductCount

import javax.persistence.EntityManager; //导入方法依赖的package包/类
/**
 * Gets the count of all Products in the Category of the given categoryId.
 * @param categoryId The id of the Category containing the Products.
 * @return Count of Products with the specified Category.
 */
public long getProductCount(long categoryId) {
	long count = -1;
	EntityManager em = getEM();
    try {
        em.getTransaction().begin();
        PersistenceCategory cat = em.find(PersistenceCategory.class, categoryId);
        if (cat != null) {
        	TypedQuery<Long> allMatchesQuery =
        			em.createQuery("SELECT COUNT(u) FROM " + getEntityClass().getName()
        					+ " u WHERE u.category = :cat", Long.class);
        	allMatchesQuery.setParameter("cat", cat);
        	Long countResult = allMatchesQuery.getSingleResult();
        	if (countResult != null) {
        		count = countResult;
        	}
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
	return count;
}
 
开发者ID:DescartesResearch,项目名称:Pet-Supply-Store,代码行数:28,代码来源:ProductRepository.java

示例5: findAll

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public List<BookEntity> findAll() {
	EntityManager em = connection.createEntityManager();
	List<BookEntity> result;
	
	try {
		em.getTransaction().begin();
		TypedQuery<BookEntity> query = em.createQuery("Select b from BookEntity b", BookEntity.class);
		result = query.getResultList();
		em.getTransaction().commit();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
	}
	
	return result;
}
 
开发者ID:PawelBogdan,项目名称:BecomeJavaHero,代码行数:19,代码来源:BookDAOImpl.java

示例6: findByIpAddress

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public static VM findByIpAddress(EntityManager em, VirtualizationConnector vc, String ipAddress) {

        String hql = "SELECT VM FROM" + " VirtualizationConnector VC" + " JOIN VC.securityGroups SG"
                + " JOIN SG.securityGroupMembers SGM" + " JOIN SGM.vm VM" + " JOIN VM.ports port"
                + " JOIN port.ipAddresses ip" + " WHERE VC.id = :vcId" + " AND ip = :ipAddress";

        TypedQuery<VM> query = em.createQuery(hql, VM.class);
        query.setParameter("vcId", vc.getId());
        query.setParameter("ipAddress", ipAddress);

        List<VM> vms = query.getResultList();

        if (!vms.isEmpty()) {
            return vms.get(0);
        } else {
            return null;
        }
    }
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:19,代码来源:VMPortEntityManager.java

示例7: findCardsByEppnInAndEtatIn

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public static TypedQuery<Card> findCardsByEppnInAndEtatIn(List<String> eppns, List<Etat> etats, String sortFieldName, String sortOrder) {
    EntityManager em = Card.entityManager();
    StringBuilder queryBuilder = new StringBuilder("SELECT o FROM Card AS o WHERE o.eppn IN (:eppns) AND o.etat IN (:etats)");
    if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
        queryBuilder.append(" ORDER BY ").append(sortFieldName);
        if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
            queryBuilder.append(" ").append(sortOrder);
        }
    }
    TypedQuery<Card> q = em.createQuery(queryBuilder.toString(), Card.class);
    q.setParameter("eppns", eppns);
    q.setParameter("etats", etats);
    return q;
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:15,代码来源:Card.java

示例8: count

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public default long count() {
    EntityManager entityManager = getEntityManager();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

    CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
    Root<E> root = criteriaQuery.from(getEntityClass());
    criteriaQuery.select(criteriaBuilder.count(root));
    TypedQuery<Long> query = entityManager.createQuery(criteriaQuery);

    return query.getSingleResult();
}
 
开发者ID:daniel-shuy,项目名称:JAX-RS-JPA-CRUD,代码行数:12,代码来源:RepositoryCRUD.java

示例9: selectJpqlQuery

import javax.persistence.EntityManager; //导入方法依赖的package包/类
/**
 * Results will be sauced if they are SaucedEntites
 *
 * @param queryString the raw JPQL query string
 * @param parameters  parameters to be set on the query
 * @param resultClass expected class of the results of the query
 * @param offset      set to -1 or lower for no offset
 * @param limit       set to -1 or lower for no limit
 */
//limited and offset results
@Nonnull
@CheckReturnValue
public <T> List<T> selectJpqlQuery(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters,
                                   @Nonnull final Class<T> resultClass, final int offset, final int limit)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final TypedQuery<T> q = em.createQuery(queryString, resultClass);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        if (offset > -1) {
            q.setFirstResult(offset);
        }
        if (limit > -1) {
            q.setMaxResults(limit);
        }

        em.getTransaction().begin();
        final List<T> resultList = q.getResultList();
        em.getTransaction().commit();
        return resultList.stream()
                         .peek(this::setSauce)
                         .collect(Collectors.toList());
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to select JPQL query %s with %s parameters, offset %s, limit %s, on DB %s",
                queryString, parameters != null ? parameters.size() : "null", offset, limit, this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
开发者ID:napstr,项目名称:SqlSauce,代码行数:43,代码来源:DatabaseWrapper.java

示例10: cleanUp

import javax.persistence.EntityManager; //导入方法依赖的package包/类
@AfterClass
public void cleanUp() {
    _logger.info("Clean up after test");

    EntityManager _em = Persistence.createEntityManager();

    TypedQuery<User> query =_em.createQuery("select u from User u where u.userName=:userName", User.class);

    query.setParameter("userName", registeredUser.getUserName());
    User _user = query.getSingleResult();

    _em.getTransaction().begin();
    _em.remove(_user);
    _em.getTransaction().commit();
}
 
开发者ID:awslabs,项目名称:aws-photosharing-example,代码行数:16,代码来源:UserFacadeTest.java

示例11: rbtn_arkadaslarItemStateChanged

import javax.persistence.EntityManager; //导入方法依赖的package包/类
private void rbtn_arkadaslarItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rbtn_arkadaslarItemStateChanged
    if (!rbtn_arkadaslar.isSelected()) {
        return;
    }

    btn_kabulet.setEnabled(false);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
    EntityManager em = emf.createEntityManager();

    Query q = em.createQuery("SELECT u FROM ARKADASLIK u WHERE u.idUserKabul=:id AND u.kabulDurumu=true");
    q.setParameter("id", Frm_Login.loginuser.getId());

    List<ARKADASLIK> gelenistekler = q.getResultList();
    dtm2.setRowCount(0);
    for (ARKADASLIK istek : gelenistekler) {

        q = em.createQuery("SELECT u FROM USER_1 u WHERE u.id=:id");
        q.setParameter("id", istek.getIdUserIstek());

        USER_1 arkadas = (USER_1) q.getSingleResult();
        if (arkadas != null) {
            dtm2.addRow(new Object[]{arkadas.getId(), arkadas.getKullaniciAdi(), arkadas.getAdi(), arkadas.getSoyadi()});
            return;
        }
    }


}
 
开发者ID:sametkaya,项目名称:Java_Swing_Programming,代码行数:30,代码来源:Frm_KullaniciSayfasi.java

示例12: findCardsByCsn

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public static TypedQuery<Card> findCardsByCsn(String csn) {
    if (csn == null || csn.length() == 0) throw new IllegalArgumentException("The csn argument is required");
    EntityManager em = entityManager();
    TypedQuery<Card> q = em.createQuery("SELECT o FROM Card AS o WHERE o.csn = upper(:csn)", Card.class);
    q.setParameter("csn", csn);
    return q;
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:8,代码来源:Card.java

示例13: getRoomCategoryByName

import javax.persistence.EntityManager; //导入方法依赖的package包/类
public RoomCategory getRoomCategoryByName(String categoryName) {
    EntityManager entityManager = HibernateUtil.getEntityManager();
    String queryString = "FROM RoomCategory WHERE name = :categoryName";
    Query q = entityManager.createQuery(queryString);
    q.setParameter("categoryName", categoryName);
    RoomCategory result = (RoomCategory) q.getSingleResult();
    entityManager.close();
    return result;
}
 
开发者ID:maillouxc,项目名称:git-rekt,代码行数:10,代码来源:RoomService.java

示例14: btn_sorgulaActionPerformed

import javax.persistence.EntityManager; //导入方法依赖的package包/类
private void btn_sorgulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_sorgulaActionPerformed
    // TODO add your handling code here:
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU");
    EntityManager em = emf.createEntityManager();

    dtm.setRowCount(0);
    Query q = em.createQuery("SELECT h FROM Hasta h WHERE h.idDoktor=:did");
    q.setParameter("did", doktorlar.get(cmb_doktorlar.getSelectedIndex()).getId());
    List<Hasta> hastalar = q.getResultList();
    for (Hasta hs : hastalar) {
        dtm.addRow(new Object[]{hs.getId(), hs.getAdi(), hs.getSoyadi(), hs.getIdDoktor()});
    }
    tbl_hastalar.setModel(dtm);

}
 
开发者ID:sametkaya,项目名称:Java_Swing_Programming,代码行数:16,代码来源:Soru1.java

示例15: getAllBooks

import javax.persistence.EntityManager; //导入方法依赖的package包/类
@Override
public List<Book> getAllBooks() {
	EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();
	
	// begining of transaction
	em.getTransaction().begin();
	Query query = em.createQuery("Select b from Book b");
	return query.getResultList();
}
 
开发者ID:PawelBogdan,项目名称:BecomeJavaHero,代码行数:11,代码来源:JPABookService.java


注:本文中的javax.persistence.EntityManager.createQuery方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。