Switch to full style
Java persistent API
Post a reply

create named query

Tue Apr 20, 2010 5:21 pm

Following code show you how to create a named query within your code (Not at orm.xml when u r are working on application server ) , Am creating here a named query using enhanced query or what it is named EJB-QL .
Code:

package com
.codemiles.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public abstract class JPAService {
    private EntityManager entityManager;

    /**
     * @param args
     */
    public void showTopics() {
    EntityManagerFactory factory = Persistence
            
.createEntityManagerFactory("persistenceUnitName");
    entityManager = factory.createEntityManager();
    entityManager.getTransaction().begin();

    List<Topic> list = loadAllTopics();
    if (list != null) {
        for (Topic currentTopic : list) {
        System.out.println("Topic id#(" + currentTopic.getId()
                + " ). Title = " + currentTopic.getTitle()
                + " , Content = " + currentTopic.getContent());
        }
    }
 
    entityManager.getTransaction().commit();
     entityManager.close();
     factory.close();

    }

    public List<Topic> loadAllTopics() {
    List<Topic> resultList = entityManager.createQuery(
            "SELECT t FROM Topic t").getResultList();

    return resultList;
    }

    public Topic loadAllTopicsById(int id) {
    return (Topic) entityManager.createQuery(
            "SELECT t FROM Topic t.id=" + id).getSingleResult();
    }
}
 




Post a reply
  Related Posts  to : create named query
 create a named query within entity class     -  
 Named Native Query     -  
 Create auto numbered column in mysql query     -  
 How are Java source code files named     -  
 EJB-QL IN where query     -  
 Run query and search from ASP     -  
 Query about jsp and printer     -  
 select query example in php     -  
 update query example     -  
 SQL AND OR in WHERE query Commands     -