Tue Apr 20, 2010 5:21 pm
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();
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.