Java Code Examples for javax.persistence.Query

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project arquillian-examples, under directory /jpalab/src/main/java/com/acme/jpa/business/.

Source file: RepositoryBean.java

  23 
vote

@Override @SuppressWarnings("unchecked") public <T>List<T> retrieveByQuery(final Class<T> entityType,final String query,final String... params){
  Query q=em.createQuery(query);
  for (int i=0; i < params.length; i++) {
    q.setParameter(i + 1,params[i]);
  }
  return (List<T>)q.getResultList();
}
 

Example 2

From project gmc, under directory /src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/data/.

Source file: PersistenceDao.java

  23 
vote

private Query createQuery(String queryString,String... params){
  Query query=getEntityManager().createQuery(queryString);
  for (int i=0; i < params.length; i++) {
    query.setParameter(i + 1,params[i]);
  }
  return query;
}
 

Example 3

From project arquillian-showcase, under directory /jpa-lite/src/main/java/com/acme/jpa/.

Source file: RepositoryBean.java

  22 
vote

@Override @SuppressWarnings("unchecked") public <T>List<T> retrieveByQuery(Class<T> type,String query,String... params){
  Query q=em.createQuery(query);
  for (int i=0; i < params.length; i++) {
    q.setParameter(i + 1,params[i]);
  }
  return (List<T>)q.getResultList();
}
 

Example 4

From project ATHENA, under directory /core/apa/src/main/java/org/fracturedatlas/athena/apa/impl/jpa/.

Source file: JpaApaAdapter.java

  22 
vote

@Override public Set<String> getTypes(){
  EntityManager em=this.emf.createEntityManager();
  Set<String> types=new HashSet<String>();
  try {
    Query query=em.createQuery("SELECT DISTINCT t.type FROM JpaRecord t");
    List<String> values=query.getResultList();
    logger.debug("PropValues are " + values.toString());
    types.addAll(values);
    return types;
  }
  finally {
    cleanup(em);
  }
}
 

Example 5

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/mail/imapsync/.

Source file: ImapHelper.java

  22 
vote

/** 
 * Tries to find the account by name.
 * @param name the name of the account
 * @return an instance of {@link Account} from the database, or<code>null</code> if  {@link Account} is not stored.
 */
public static Account getAccount(String name){
  Query allAccountQuery=entityManager.createQuery("select a from Account a where a.name = :name").setParameter("name",name);
  @SuppressWarnings("unchecked") List<Account> list=allAccountQuery.getResultList();
  if (list == null || list.size() == 0) {
    return null;
  }
  return list.get(0);
}
 

Example 6

From project camel-aries-blueprint-tutorial, under directory /reportincident.persistence-jpa-aries/src/main/java/org/apache/camel/example/reportincident/dao/impl/.

Source file: IncidentDAOImpl.java

  22 
vote

public List<Incident> findIncident(String key){
  Query q=this.em.createQuery("select i from Incident as i where i.incidentRef = :ref");
  q.setParameter("ref",key);
  List list=q.getResultList();
  return list;
}
 

Example 7

From project camel-osgi-servicemix-tutorial, under directory /persistence-jpa/src/main/java/org/fusesource/devoxx/reportincident/dao/impl/.

Source file: IncidentDAOImpl.java

  22 
vote

public List<Incident> findIncident(String key){
  Query q=this.em.createQuery("select i from Incident as i where i.incidentRef = :ref");
  q.setParameter("ref",key);
  List list=q.getResultList();
  return list;
}
 

Example 8

From project camel-persistence-part2, under directory /dao/src/main/java/com/fusesource/examples/persistence/part2/dao/impl/.

Source file: IncidentDAOImpl.java

  22 
vote

public List<Incident> findIncident(String key){
  Query q=this.em.createQuery("select i from Incident as i where i.incidentRef = :ref");
  q.setParameter("ref",key);
  List list=q.getResultList();
  return list;
}
 

Example 9

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/ui/.

Source file: SqlCommand.java

  22 
vote

@SuppressWarnings({"unchecked"}) @Security({"admin","editor"}) @Transactional @Proxying(ProxyingEnum.DISABLE) public void executeSelect(){
  String query=getParameter("select","query");
  EntityManager em=emInjector.getEM();
  Query q=em.createQuery(query);
  results=q.getResultList();
}
 

Example 10

From project datavalve, under directory /datavalve-jpa/src/main/java/org/fluttercode/datavalve/provider/jpa/.

Source file: AbstractJpaDataProvider.java

  22 
vote

/** 
 * Initializes a JPA  {@link Query} using the passed in {@link DataQuery}. The type of query returned is determined from the {@link AbstractJpaDataProvider#createJpaQuery(String)} method which canreturn a native or EJBQL query depending on the subclass.
 * @param dataQuery The  {@link DataQuery} to initialize the query with
 * @return The initialized {@link Query}
 */
private final Query buildJpaQuery(DataQuery dataQuery){
  Query qry=createJpaQuery(dataQuery.getStatement());
  for (  Parameter param : dataQuery.getParameters()) {
    qry.setParameter(param.getName(),param.getValue());
  }
  return qry;
}
 

Example 11

From project demoiselle-contrib, under directory /archetype/demoiselle-jsf-fuselage/src/main/java/br/gov/frameworkdemoiselle/archetype/fuselage/bookmark/persistence/.

Source file: BookmarkDAO.java

  22 
vote

@SuppressWarnings("unchecked") public List<Bookmark> findByCategory(String category,String search){
  String q="from Bookmark as b where lower(b.category) = lower(:category) and" + "(lower(b.description) like lower(:search) or lower(b.link) like lower(:search)) ";
  Query query=createQuery(q);
  query.setParameter("category",category);
  query.setParameter("search","%" + search + "%");
  return query.getResultList();
}
 

Example 12

From project devoxx-2011-hands-on-lab, under directory /persistence-jpa/src/main/java/org/fusesource/devoxx/reportincident/dao/impl/.

Source file: IncidentDAOImpl.java

  22 
vote

public List<Incident> findIncident(String key){
  Query q=this.em.createQuery("select i from Incident as i where i.incidentRef = :ref");
  q.setParameter("ref",key);
  List list=q.getResultList();
  return list;
}
 

Example 13

From project Empire, under directory /test/src/com/clarkparsia/empire/test/.

Source file: EntityManagerTestSuite.java

  22 
vote

/** 
 * Test to verify that setting the parameter of a query w/ a java.net.URI works and does not result in an NPE
 */
@Test public void testSettingQueryParameterAsURI(){
  EntityManager aManager=createEntityManager();
  try {
    Query aQuery=aManager.createQuery("select ?s where { ?s ??p ?o }");
    aQuery.setParameter("p",URI.create("urn:p"));
  }
  finally {
    aManager.close();
  }
}
 

Example 14

From project faces_1, under directory /examples/short-ly/src/main/java/org/jboss/seam/faces/examples/shortly/.

Source file: LinkBean.java

  22 
vote

@SuppressWarnings("unchecked") public TinyLink getByKey(final String key){
  Query query=em.createQuery("select t from TinyLink t where t.name=:key",TinyLink.class);
  query.setParameter("key",key);
  List<TinyLink> resultList=query.getResultList();
  if (resultList.isEmpty()) {
    return new TinyLink();
  }
  return resultList.get(0);
}
 

Example 15

From project framework, under directory /impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/template/.

Source file: JPACrud.java

  22 
vote

/** 
 * Search JPQL integrated into the context of paging
 * @param jpql - query in syntax JPQL
 * @return a list of entities
 */
protected List<T> findByJPQL(String jpql){
  TypedQuery<T> listQuery=getEntityManager().createQuery(jpql,getBeanClass());
  if (getPagination() != null) {
    String countQuery=createCountQuery(jpql);
    Query query=getEntityManager().createQuery(countQuery);
    Number cResults=(Number)query.getSingleResult();
    getPagination().setTotalResults(cResults.intValue());
    listQuery.setFirstResult(getPagination().getFirstResult());
    listQuery.setMaxResults(getPagination().getPageSize());
  }
  return listQuery.getResultList();
}
 

Example 16

From project gadget-server, under directory /gadget-core/src/main/java/org/overlord/gadgets/server/service/.

Source file: ApplicationDataManagerImpl.java

  22 
vote

public ApplicationData getApplicationData(String userId,String appUrl){
  if (!entityManager.getTransaction().isActive()) {
    entityManager.getTransaction().begin();
  }
  Query query=entityManager.createQuery("select app from ApplicationData app where app.userId = :userId and app.appUrl = :appUrl");
  query.setParameter("userId",userId);
  query.setParameter("appUrl",appUrl);
  List<ApplicationData> data=query.getResultList();
  entityManager.getTransaction().commit();
  if (data == null) {
    return null;
  }
  return data.get(0);
}
 

Example 17

From project GNDMS, under directory /dspace/src/de/zib/gndms/logic/model/dspace/.

Source file: SliceKindProviderImpl.java

  22 
vote

@Override public List<String> list(String subspace) throws NoSuchElementException {
  EntityManager em=emf.createEntityManager();
  Query query=em.createNamedQuery(getListQuery());
  query.setParameter("idParam",subspace);
  return query.getResultList();
}
 

Example 18

From project google-app-engine-jappstart, under directory /src/main/java/com/jappstart/service/auth/.

Source file: PersistentTokenRepositoryImpl.java

  22 
vote

/** 
 * Creates a new remember me token.
 * @param token the remember me token
 */
@Override @Transactional public final void createNewToken(final PersistentRememberMeToken token){
  final Query query=entityManager.createQuery("SELECT u FROM UserAccount u WHERE username = :username");
  query.setParameter("username",token.getUsername());
  final UserAccount user=(UserAccount)query.getSingleResult();
  if (user.getPersistentUser() == null) {
    user.setPersistentUser(new PersistentUser(user.getKey(),token.getUsername()));
  }
  if (user.getPersistentUser().getPersistentLogins() == null) {
    user.getPersistentUser().setPersistentLogins(new ArrayList<PersistentLogin>());
  }
  user.getPersistentUser().getPersistentLogins().add(createPersistentLogin(user.getPersistentUser().getKey(),token));
  entityManager.persist(user);
  memcacheService.put(user.getUsername(),user,Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
}
 

Example 19

From project happening, under directory /src-domain/org/vaadin/training/fundamentals/happening/domain/impl/.

Source file: DefaultDomain.java

  22 
vote

@SuppressWarnings("unchecked") @Override public <A extends AbstractEntity>List<A> list(Class<A> clazz){
  EntityManager em=getEntityManager();
  try {
    ExpressionBuilder builder=new ExpressionBuilder();
    JpaEntityManager jpaEm=JpaHelper.getEntityManager(em);
    Query query=jpaEm.createQuery(builder,clazz);
    return query.getResultList();
  }
  finally {
    em.close();
  }
}
 

Example 20

From project james-mailbox, under directory /jpa/src/main/java/org/apache/james/mailbox/jpa/mail/.

Source file: JPAMessageMapper.java

  22 
vote

/** 
 * @see org.apache.james.mailbox.store.mail.MessageMapper#findRecentMessageUidsInMailbox(Mailbox)
 */
@SuppressWarnings("unchecked") public List<Long> findRecentMessageUidsInMailbox(Mailbox<Long> mailbox) throws MailboxException {
  try {
    Query query=getEntityManager().createNamedQuery("findRecentMessageUidsInMailbox").setParameter("idParam",mailbox.getMailboxId());
    return query.getResultList();
  }
 catch (  PersistenceException e) {
    throw new MailboxException("Search of recent messages failed in mailbox " + mailbox,e);
  }
}
 

Example 21

From project java-maven-tests, under directory /src/jappstart-gwitter/src/main/java/com/jappstart/service/auth/.

Source file: PersistentTokenRepositoryImpl.java

  22 
vote

/** 
 * Creates a new remember me token.
 * @param token the remember me token
 */
@Override @Transactional public final void createNewToken(final PersistentRememberMeToken token){
  final Query query=entityManager.createQuery("SELECT u FROM UserAccount u WHERE username = :username");
  query.setParameter("username",token.getUsername());
  final UserAccount user=(UserAccount)query.getSingleResult();
  if (user.getPersistentUser() == null) {
    user.setPersistentUser(new PersistentUser(user.getKey(),token.getUsername()));
  }
  if (user.getPersistentUser().getPersistentLogins() == null) {
    user.getPersistentUser().setPersistentLogins(new ArrayList<PersistentLogin>());
  }
  user.getPersistentUser().getPersistentLogins().add(createPersistentLogin(user.getPersistentUser().getKey(),token));
  entityManager.persist(user);
  memcacheService.put(user.getUsername(),user,Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
}
 

Example 22

From project jboss-as-quickstart, under directory /greeter/src/main/java/org/jboss/as/quickstarts/greeter/domain/.

Source file: EJBUserDao.java

  22 
vote

public User getForUsername(String username){
  try {
    Query query=entityManager.createQuery("select u from User u where u.username = ?");
    query.setParameter(1,username);
    return (User)query.getSingleResult();
  }
 catch (  NoResultException e) {
    return null;
  }
}
 

Example 23

From project jms, under directory /examples/jms-statuswatcher/src/main/java/org/jboss/seam/jms/example/statuswatcher/session/.

Source file: StatusManagerImpl.java

  22 
vote

public List<Status> getAllStatuses(){
  Query q=em.createQuery("SELECT s from Status s ORDER BY datetime DESC");
  q.setMaxResults(MAX_RESULTS);
  @SuppressWarnings("unchecked") List<Status> stats=q.getResultList();
  return stats;
}
 

Example 24

From project Kundera-Examples, under directory /src/main/java/com/impetus/kundera/examples/crossdatastore/pickr/dao/.

Source file: PickrImpl.java

  22 
vote

@Override public List<Object> getAllPhotographers(String className){
  EntityManager em=getEntityManager();
  Query q=em.createQuery("select p from " + className + " p");
  List<Object> photographers=q.getResultList();
  return photographers;
}
 

Example 25

From project laboratory, under directory /auction5/src/main/java/br/gov/serpro/auction5/persistence/.

Source file: AuctionDAO.java

  22 
vote

public List<Auction> listOpenAuctionsByCategory(Category category){
  String jpql="select a from Auction a " + "where a.status = :status " + "  and a.deadline > :deadline "+ "  and a.item.category = :category "+ "order by a.item.description";
  Query query=createQuery(jpql);
  query.setParameter("status",Status.OPEN);
  query.setParameter("deadline",new Date());
  query.setParameter("category",category);
  return query.getResultList();
}
 

Example 26

From project lightweightEE, under directory /backend/src/main/java/de/jaxenter/eesummit/caroline/backend/impl/.

Source file: CustomerServiceImpl.java

  22 
vote

@Override public List<Customer> searchCustomers(String lastName,String firstName){
  QueryBuilder qb=new QueryBuilder("SELECT c from Customer AS c");
  if (lastName != null && lastName.length() > 0) {
    qb.addQueryPart("c.lastName like :lastName","lastName",lastName.replace('*','%'));
  }
  if (firstName != null && firstName.length() > 0) {
    qb.addQueryPart("c.firstName like :firstName","firstName",firstName.replace('*','%'));
  }
  Query q=qb.getQuery(em);
  return q.getResultList();
}
 

Example 27

From project ManalithBot, under directory /ManalithBotWeb/app/controllers/plugin/dictionary/.

Source file: Application.java

  22 
vote

@Transactional(readOnly=true) public static Result show(String word){
  Query query=JPA.em().createQuery("SELECT w FROM Word w WHERE w.word=:word ORDER BY w.id DESC");
  query.setParameter("word",word);
  Word w=(Word)query.setMaxResults(1).getSingleResult();
  return ok(show.render(w));
}
 

Example 28

From project ndg, under directory /ndg-server-core/src/main/java/br/org/indt/ndg/server/authentication/.

Source file: UserManagerBean.java

  22 
vote

public Collection<RoleVO> listAllRoles() throws MSMApplicationException {
  ArrayList<RoleVO> ret=new ArrayList<RoleVO>();
  Query q=manager.createQuery("from NdgRole");
  ArrayList<NdgRole> roles=(ArrayList<NdgRole>)q.getResultList();
  for (  NdgRole role : roles) {
    RoleVO vo=new RoleVO();
    vo.setName(role.getRoleName());
    ret.add(vo);
  }
  return ret;
}
 

Example 29

From project netnumeri, under directory /lib/gwt-2.5.0.rc1/samples/Expenses/src/main/java/com/google/gwt/sample/expenses/server/domain/.

Source file: Employee.java

  22 
vote

public static long countEmployeesByDepartment(String department){
  EntityManager em=entityManager();
  try {
    Query query=em.createQuery("select count(o) from Employee o where o.department=:department");
    query.setParameter("department",department);
    return ((Number)query.getSingleResult()).longValue();
  }
  finally {
    em.close();
  }
}
 

Example 30

From project nuxeo-services, under directory /nuxeo-platform-placeful-core/src/main/java/org/nuxeo/ecm/platform/ec/placeful/.

Source file: PlacefulServiceImpl.java

  22 
vote

public Annotation getAnnotation(EntityManager em,String id,String name){
  String className=registry.get(name);
  String shortClassName=getShortName(className);
  Query query=em.createQuery("FROM " + shortClassName + " WHERE id=:id");
  query.setParameter("id",id);
  return (Annotation)query.getSingleResult();
}
 

Example 31

From project odata4j, under directory /odata4j-core/src/main/java/org/odata4j/producer/jpa/.

Source file: ExecuteCountQueryCommand.java

  22 
vote

@Override public boolean execute(JPAContext context){
  String jpql=context.getJPQLQuery();
  Query tq=context.getEntityManager().createQuery(jpql);
  Long count=(Long)tq.getSingleResult();
  QueryInfo query=context.getQueryInfo();
  if (query != null && query.skip != null)   count=Math.max(0,count - query.skip);
  if (query != null && query.top != null)   count=Math.min(count,query.top);
  context.setResult(JPAResults.count(count));
  return false;
}
 

Example 32

From project ODE-X, under directory /repo/src/main/java/org/apache/ode/repo/.

Source file: RepositoryImpl.java

  22 
vote

protected ArtifactImpl loadArtifact(QName qname,String contentType,String version) throws RepositoryException {
  Query q=mgr.createNamedQuery("lookupArtifact");
  q.setParameter("qname",qname.toString());
  q.setParameter("type",contentType);
  q.setParameter("version",version);
  try {
    return (ArtifactImpl)q.getSingleResult();
  }
 catch (  NoResultException nr) {
    throw new RepositoryException(String.format("Artifact qname %s contentType %s version %s does not exists",qname,contentType,version),nr);
  }
}
 

Example 33

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/.

Source file: JpaEventRepository.java

  22 
vote

@SuppressWarnings("unchecked") @Override @Transactional public Collection<Event> getEventsDuringPeriod(Date start,Date end,int startChunk,int chunkSize){
  Query query=manager.createQuery("SELECT e FROM Event e WHERE e.timestamp BETWEEN :start AND :end");
  query=query.setParameter("start",start,TemporalType.DATE);
  query=query.setParameter("end",end,TemporalType.DATE);
  query=query.setFirstResult(startChunk);
  query=query.setMaxResults(chunkSize);
  return query.getResultList();
}
 

Example 34

From project OpenMEAP, under directory /server-side/openmeap-shared-serverside/src/com/openmeap/model/.

Source file: ModelServiceImpl.java

  22 
vote

@SuppressWarnings("unchecked") public <T extends ModelEntity>List<T> findAll(Class<T> clazz){
  Query q=entityManager.createQuery("select distinct a from " + clazz.getCanonicalName() + " a");
  try {
    return q.getResultList();
  }
 catch (  NoResultException nre) {
    return null;
  }
}
 

Example 35

From project FIP3A, under directory /IR330/IR331/version1/GestionRH/GestionRH-ejb/src/java/systeme/.

Source file: GestionRH.java

  21 
vote

@Override public Boolean peuplerBase(Integer nombre){
  GesEmploye e=new GesEmploye();
  String prenomEmp="lePrenomEmp";
  String nomEmp="leNomEmp";
  String poste="lePosteEmp";
  GesOffre o=new GesOffre();
  String titre="leTitre";
  String mission="laMission";
  Integer salaire=35000;
  GesCandidat c=new GesCandidat();
  String prenomCan="lePrenomCan";
  String nomCan="leNomCan";
  for (  Convocation convocation : c.listerConvocations()) {
    c.supprimerConvocation(convocation);
  }
  for (  Dossier dossier : c.listerDossiers()) {
    c.supprimerDossier(dossier);
  }
  for (  Offre offre : o.listerOffres()) {
    o.supprimerOffre(offre);
  }
  for (  Candidat candidat : c.listerCandidats()) {
    c.suppprimerCandidat(candidat);
  }
  for (  Employe employe : e.listerEmployes()) {
    e.supprimerEmploye(employe);
  }
  Query q1=em.createNativeQuery("SELECT setval('off_seq', 1);");
  List resultList1=q1.getResultList();
  Query q2=em.createNativeQuery("SELECT setval('can_seq', 1);");
  List resultList2=q2.getResultList();
  Query q3=em.createNativeQuery("SELECT setval('emp_seq', 1);");
  List resultList3=q3.getResultList();
  Query q4=em.createNativeQuery("SELECT setval('hibernate_sequence', 1);");
  List resultList4=q4.getResultList();
  for (int i=0; i < nombre; i++) {
    o.creerOffre(titre + i,mission + i,salaire + i,e.creerEmploye(prenomEmp + i,nomEmp + i,poste + i));
  }
  return true;
}
 

Example 36

From project guice-jit-providers, under directory /extensions/persist/src/com/google/inject/persist/jpa/.

Source file: JpaFinderProxy.java

  21 
vote

public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  EntityManager em=emProvider.get();
  JpaFinderProxy.FinderDescriptor finderDescriptor=getFinderDescriptor(methodInvocation);
  Object result=null;
  Query jpaQuery=finderDescriptor.createQuery(em);
  if (finderDescriptor.isBindAsRawParameters) {
    bindQueryRawParameters(jpaQuery,finderDescriptor,methodInvocation.getArguments());
  }
 else {
    bindQueryNamedParameters(jpaQuery,finderDescriptor,methodInvocation.getArguments());
  }
  if (JpaFinderProxy.ReturnType.PLAIN.equals(finderDescriptor.returnType)) {
    result=jpaQuery.getSingleResult();
  }
 else   if (JpaFinderProxy.ReturnType.COLLECTION.equals(finderDescriptor.returnType)) {
    result=getAsCollection(finderDescriptor,jpaQuery.getResultList());
  }
 else   if (JpaFinderProxy.ReturnType.ARRAY.equals(finderDescriptor.returnType)) {
    result=jpaQuery.getResultList().toArray();
  }
  return result;
}
 

Example 37

From project ISAvalidator-ISAconverter-BIImanager, under directory /import_layer/src/test/java/org/isatools/isatab/.

Source file: ISATABUnloadTest.java

  21 
vote

@Test public void testUnloading() throws Exception {
  out.println("\n\n_______________________ ISATAB Unloading Test _______________________\n\n");
  String baseDir=System.getProperty("basedir");
  String filesPath=baseDir + "/target/test-classes/test-data/isatab/isatab/example";
  ISATABLoader loader=new ISATABLoader(filesPath);
  FormatSetInstance isatabInstance=loader.load();
  BIIObjectStore store=new BIIObjectStore();
  ISATABMapper isatabMapper=new ISATABMapper(store,isatabInstance);
  isatabMapper.map();
  assertTrue("Oh no! No mapped object! ",store.size() > 0);
  out.println("\n_____________ Persisting " + store.size() + " objects:\n");
  ISATABPersister persister=new ISATABPersister(store,DaoFactory.getInstance(entityManager));
  Timestamp ts=persister.persist(filesPath);
  transaction.commit();
  out.println("\n\n\n\n________________ Done, Submission TS: " + ts.getTime() + " ("+ ts+ " + "+ ts.getNanos()+ "ns)");
  Collection<Study> studies=store.valuesOfType(Study.class);
  Study study=studies.iterator().next();
  session.flush();
  ISATABUnloader unloader=new ISATABUnloader(DaoFactory.getInstance(entityManager),ts);
  unloader.unload();
  out.println("Unloading executed, messages: " + unloader.getMessages());
  Query q=entityManager.createQuery("SELECT e FROM " + Identifiable.class.getName() + " e WHERE e.submissionTs = :ts");
  q.setParameter("ts",ts);
  boolean isAllUnloaded=true;
  for (  Object o : q.getResultList()) {
    out.println("**** Oh No! I have found an entity that should be unloaded! " + o);
    isAllUnloaded=false;
  }
  assertTrue("Sigh! I still have some objects that were not unloaded",isAllUnloaded);
  out.println("\n\n___________________ /end: ISATAB Unloading Test ___________________\n\n");
}
 

Example 38

From project JPA-NestedSet, under directory /src/main/java/org/code_factory/jpa/nestedset/.

Source file: JpaNode.java

  21 
vote

/** 
 * {@inheritDoc}
 */
@Override public void delete(){
  int oldRoot=getRootValue();
  String rootIdFieldName=nsm.getConfig(this.type).getRootIdFieldName();
  String leftFieldName=nsm.getConfig(this.type).getLeftFieldName();
  String rightFieldName=nsm.getConfig(this.type).getRightFieldName();
  StringBuilder sb=new StringBuilder();
  sb.append("delete from ").append(node.getClass().getSimpleName()).append(" n").append(" where n.").append(leftFieldName).append(">= ?1").append(" and n.").append(rightFieldName).append("<= ?2");
  if (rootIdFieldName != null) {
    sb.append(" and n.").append(rootIdFieldName).append("= ?3");
  }
  Query q=nsm.getEntityManager().createQuery(sb.toString());
  q.setParameter(1,getLeftValue());
  q.setParameter(2,getRightValue());
  if (rootIdFieldName != null) {
    q.setParameter(3,oldRoot);
  }
  q.executeUpdate();
  int first=getRightValue() + 1;
  int delta=getLeftValue() - getRightValue() - 1;
  shiftRLValues(first,0,delta,oldRoot);
  nsm.removeNodes(getLeftValue(),getRightValue(),oldRoot);
}
 

Example 39

From project hibernate-ogm, under directory /hibernate-ogm-core/src/main/java/org/hibernate/ogm/jpa/impl/.

Source file: OgmEntityManager.java

  19 
vote

@Override public Query createQuery(String qlString){
  if (qlString != null && qlString.toLowerCase().startsWith("delete from")) {
    return new LetThroughExecuteUpdateQuery();
  }
  throw new NotSupportedException("OGM-21","JP-QL queries are not supported yet");
}