spring mvc hiberate, use CriteriaQuery to run select * from table where - sql

what i need is to run a sql query something like :
select * from table where alpahbetcolumn="A" and numbercolumn="10" and shelfcolumn="upper";
i want to know how to do this query in hibernate using EntityManager
currently this is my own try out, but not working....
#PersistenceContext
EntityManager em;
#Transactional
public List<Item> listItems(String alpahbet, String number, String shelf) {
CriteriaQuery<Item> c = em.getCriteriaBuilder().createQuery(Item.class);
c.from(Item.class);
c..where( em.equal( alpahbet, "alpahbetcolumn" ) && em.equal( number, "numbercolumn" ) && em.equal( shelf, "shelfcolumn" ));
return em.createQuery(c).getResultList();
}
i only have a very vague understanding on spring hibernate topic..still learning...
can someone please point me out how to do this sql query properly, with code example. thanks

Try this
Query q = em.createNativeQuery("select * from table where alpahbetcolumn='A' and numbercolumn= 10 and shelfcolumn='upper'");
q.getResultList();
createNativeQuery() accepts plain SQL as parameter. If you expect Item as result, you can use this
em.createNativeQuery("select * from table where alpahbetcolumn='A' and numbercolumn= 10 and shelfcolumn='upper'", Item.class);
If you want to use JPQL (JPA Query Language), then we need your entity code to be sure, but it would be something like this
em.createQuery("select i from Item i where i.alphabetColumn = 'A' ");
For parameterized queries, use this
Query q = em.createNativeQuery("select * from table where alpahbetcolumn=? and numbercolumn=? and shelfcolumn=?");
q.setParameter(1, "A");
q.setParameter(2, 10);
q.setParameter(3, "upper");

HQL is like this:
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append(" FROM table");
queryBuilder.append(" WHERE alpahbetcolumn= :codeA");
queryBuilder.append(" AND numbercolumn= :numColumn");
queryBuilder.append(" AND shelfcolumn= :upper");
Query query = getSession().createQuery(queryBuilder.toString());
query = query.setParameter("codeA", "A");
query.setParameter("numColumn", "10");
query.setParameter("upper", "upper");
query.list(); to get your result ;)
and getSession() come from :
private SessionFactory sessionFactory;
#Required
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
see spring configuration to configure your sessionfactory ;)
or if you use JPA try this link
get session from entityManager

i have worked out using criteriaquery to fullfill my needs, here is the code. it works
#Transactional
public List<Item> listItems(String alpahbet, String number, String shelf) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
criteriaQuery.select(itemRoot).where(criteriaBuilder.equal(itemRoot.get("alpahbetField"), alpahbet), criteriaBuilder.equal(itemRoot.get("numberField"), number), criteriaBuilder.equal(itemRoot.get("shelfField"), shelf));
return em.createQuery(criteriaQuery).getResultList();
}

Related

Ignite SqlQuery for complex java objects

In my cache I have a complex java object as below -
class Person{
private Department d;
....
}
class Department {
private Department code;
....
}
I am using below SQLQuery to read it -
SqlQuery<Short, BinaryObject> query = new SqlQuery<>(Person.class, "d.code = ?");
String args="101"; // department code
QueryCursor<Cache.Entry<Short, BinaryObject>> resultSet = personCache.query(query.setArgs(args))
I am getting below error -
Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to parse query: SELECT "PERSON_CACHE"."PERSONENTITY"._KEY, "TPERSON_CACHE"."PERSONENTITY"._VAL FROM "PERSON_CACHE"."PERSONENTITY" WHERE id.code = ?
Am I doing anything wrong here ?
You can access nested fields, but only if they were configured with QuerySqlField annotation in advance:
class Person{
private Department d;
...
}
class Department {
#QuerySqlField
private Department code;
....
}
SqlQuery<Short, BinaryObject> query = new SqlQuery<>(Person.class, "code = ?");
Destructuring is not supported by Ignite SQL and there are no solid plans to implement it.
This means you can't peek into fields that are rich objects, maps, lists, etc. You should introduce a departmentId numeric field here.
Theoretically you could also try putting #QuerySqlField annotation on Department's field code, and then access it as CODE = ?. Your mileage may vary. I for one would like to hear about the result of such experiment.
I resolved it by using predicate.
IgniteBiPredicate<Long, BinaryObject> predicate = new IgniteBiPredicate<Long, BinaryObject>() {
#Override
public boolean apply(Long e1, BinaryObject e2) {
Person p= e2.deserialize();
short s = (short) args[0];
return p.getId().getCode == s;
}
};

JPA entitymanager run native sql query to get everything out from a table

What I need to do is to run a piece of native sql query to select everything and get
data out from a specific table.
My app is a spring hibernate based web app. Here is my code:
DAOserviceImpl:
#Service
public class ItemServiceImpl implements ItemService {
#PersistenceContext
EntityManager em;
#Transactional
public void addItem(Item item) {
em.persist(item);
}
#Transactional
public List<Item> iosADVsearchResults(String itemCode) {
//run native query with jpa
List<Item> itemList = (List<Item>)em.createQuery("SELECT * FROM item itemcode='" + itemCode + "'")
.getResultList();
return itemList;
}
}
but what I eventually get is this error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: = near line 1, column 35 [SELECT itemcode FROM item itemcode='ll3369']
I was following this tutorial: http://www.oracle.com/technetwork/articles/vasiliev-jpql-087123.html
Please help, any code example would be helpful.
If You are using JPA your query to get all records should be like this:
List<Item> itemList = (List<Item>) em.createQuery("SELECT i FROM item where itemcode=?1)
.setParameter(1, itemcode)
.getResultList();
this will return all the record which matches the parameter itemcode ..
em.createQuery() expects a query written in JPQL, not SQL (see this for some info). For SQL query, use em.createNativeQuery()
List<Item> itemList = (List<Item>)em.createNativeQuery("SELECT * FROM item WHERE itemcode='" + itemCode + "'", Item.class).getResultList();

Is it possible to cast a SqlQuery results from Ebean to a Model (Bean)?

Using Ebean (via Play Framework 2.1.1), I have to build a home made SQL query, but I'd like it to return directly a List<MyModel>, instead of a List<SqlRow> that I would have to query the database for each id from the result to have a List<MyModel>.
Is it possible to cast directly a SqlQuery/SqlRow to a Model ?
Actually, I do that :
SqlQuery query = Ebean.createSqlQuery("SELECT id FROM MyModel WHERE ...");
List<SqlRow> rows = query.findList(); // not directly possible.
List<MyModel> results = new ArrayList<MyModel>();
for (SqlRow row : rows) {
results.add(MyModel.find.idEq(row.getLong("id)));
}
Ideally, it would be something like :
SqlQuery query = Ebean.createSqlQuery("SELECT id FROM MyModel WHERE ...");
List<MyModel> results = (List<MyModel>) query.findList(); // not directly possible.
This is not very efficient.
Try this:
RawSql rawSql = RawSqlBuilder.parse("SELECT id, value, ... FROM MyModel WHERE ...")
.columnMapping("id", "id")
.columnMapping("value", "value")
//...
.create();
Query<MyModel> query = Ebean.find(MyModel.class);
query.setRawSql(rawSql);
List<MyModel> result = query.findList();
Or using the finder:
Finder<Long, MyModel> finder = new Finder<Long, MyModel>(Long.class, MyModel.class);
List<MyModel> result = finder.where()
.eq("name", "Barack Obama")
//...
.findList();

How to handle null pointer exceptions in elasticsearch

I'm using elasticsearch and i was trying to handle the case when the database is empty
#SuppressWarnings("unchecked")
public <M extends Model> SearchResults<M> findPage(int page, String search, String searchFields, String orderBy, String order, String where) {
BoolQueryBuilder qb = buildQueryBuilder(search, searchFields, where);
Query<M> query = (Query<M>) ElasticSearch.query(qb, entityClass);
// FIXME Currently we ignore the orderBy and order fields
query.from((page - 1) * getPageSize()).size(getPageSize());
query.hydrate(true);
return query.fetch();
}
the error at return query.fetch();
i'm trying to implement a try and catch statement but it's not working, any one can help with this please?

Is there a way to do a "in" statment in javax.persistence.Query [duplicate]

I have the following parametrised JPA, or Hibernate, query:
SELECT entity FROM Entity entity WHERE name IN (?)
I want to pass the parameter as an ArrayList<String>, is this possible? Hibernate current tells me, that
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String
Is this possible at all?
ANSWER: Collections as parameters only work with named parameters like ":name", not with JDBC style parameters like "?".
Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:
String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
For Hibernate's, you'll need to use the setParameterList:
String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:
Entity.java:
#Entity
#NamedQueries({
#NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
#Column(name = "attribute")
private String attribute;
}
Dao.java:
public class Dao {
public List<Entity> findByAttributes(Set<String> attributes) {
Query query = em.createNamedQuery("byAttributes");
query.setParameter(1, attributes);
List<Entity> entities = query.getResultList();
return entities;
}
}
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue