Created
February 15, 2011 23:24
-
-
Save searls/828504 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package blerg; | |
import static org.apache.commons.lang.StringUtils.*; | |
import java.util.List; | |
import java.util.Scanner; | |
import javax.persistence.EntityManager; | |
import javax.persistence.PersistenceContext; | |
import javax.persistence.Query; | |
import org.apache.commons.lang.builder.ToStringBuilder; | |
import org.junit.Before; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.springframework.test.context.ContextConfiguration; | |
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | |
import org.springframework.transaction.annotation.Transactional; | |
@Transactional | |
@RunWith(SpringJUnit4ClassRunner.class) | |
@ContextConfiguration(locations = { "/appContext.xml" }) | |
public class JpqlShellUtility { | |
@PersistenceContext private EntityManager em; | |
@Test | |
public void executeShell() { | |
Scanner scanner = new Scanner(System.in); | |
String query; | |
do { | |
System.out.print("> "); | |
query = scanner.nextLine(); | |
try { | |
System.out.print(performQuery(query)); | |
} catch(Exception e) { | |
e.printStackTrace(); | |
} | |
} while(!trim(query).equals("quit")); | |
} | |
@SuppressWarnings("unchecked") | |
private String performQuery(String jpql) { | |
if(isBlank(jpql)) return ""; | |
Query query = em.createQuery(jpql).setMaxResults(10); | |
List<Object> results = query.getResultList(); | |
StringBuilder sb = new StringBuilder(); | |
sb.append("Found ").append(results.size()).append(" records.\n"); | |
for (Object object : results) { | |
sb.append(ToStringBuilder.reflectionToString(object)).append("\n"); | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment