Query all items in table that does not have a relation to other item in other table in ORMLITE - ormlite

I have two tables StockItem and StockItemGroup. There is many to many relation between those tables made by StockItemGroupStockItem table. I need to make query that queries for all StockItems that does not have relation to any StockItemGroup. I have tried this code, but it does not work:
QueryBuilder<StockItemEntity, Long> qbSI = stockItemDao.queryBuilder();
QueryBuilder<StockItemGroupStockItemEntity, Long> qbSIG_SI = stockItemGroupStockItemDao.queryBuilder();
List<StockItemEntity> stockItemEntitiesWithoutGroup = null;
qbSI.where().not().exists(qbSIG_SI);
stockItemEntitiesWithoutGroup = qbSI.query();

I have found the solution. I was missing code that maps relation between two tables:
qbSIG_SI.where().eq(StockItemGroupStockItemEntity.STOCK_ITEM_ID, new ColumnArg(StockItemEntity.TABLE_NAME, StockItemEntity.ID_FIELD_NAME));

Related

OrderBy Expression When Using An Association Table

I have two tables: CommentCategories and Comments. It is a many-to-many relationship. There is a CommentCategory_Comment association table. But that table contains a orderOfCommentInCategory field, so EF represents the association by creating a seperate entity rather than navigation properties.
I am trying to get the comments under a certain category and orer them by the orderOfCommentInCategory field. How should be the OrderBy expression that needs to be added to the query below?
List<Comment> comments = category.CommentCategory_Comment
.Select(ccc=>ccc.Comment)
.OrderBy(???)
.ToList();
As #GertArnold recommends the only you need to do is order first before select:
var comments = category.CommentCategory_Comment
.OrderBy(c=>c.orderOfCommentInCategory )
.Select(ccc=>ccc.Comment)
.ToList();
Using query syntax:
var query= from cc in category.CommentCategory_Comment
orderby cc.orderOfCommentInCategory
select cc.Comment;
var comments=query.ToList();

TypedQuery<x> returns vector of Object[] instead of list of x-type object

I have a method:
public List<Timetable> getTimetableTableForRegion(String id) {
List<Timetable> timetables;
TypedQuery<Timetable> query = em_read.createQuery("SELECT ..stuff.. where R.id = :id", Timetable.class).setParameter("id", Long.parseLong(id));
timetables = query.getResultList();
return timetables;
}
which returns this:
so, what am I missing in order to return a list of Timetable's?
ok, so, ..stuff.. part of my JPQL contained an inner join to other table. Even through in SELECT there were selected fields just from one table, which was used as type - Timetable, Eclipslink was unable to determine if this fields are part of that entity and instead of returning list of defined entity returned list of Object[].
So in conclusion: Use #OneToMany/#ManyToOne mappings (or flat table design) and query just for ONE table in your JPQL to be able to typize returned entities.
Not sure it might be something is looking for, but I had similar problem and converted Vector to ArrayList like this:
final ArrayList<YourClazz> results = new ArrayList<YourClazz>();;
for ( YourClazzkey : (Vector<YourClazz>) query.getResultList() )
{
results.add(key);
}
i have faced the same problem. and my entity has no one to one or one to many relationship. then also jpql was giving me queryresult as vector of objects. i changed my solution to query to criteria builder. and that worked for me.
code snippet is as below:
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Timetable> criteria = builder.createQuery(Timetable.class);
Root<Enumeration> root = criteria.from(Timetable.class);
criteria.where(builder.equal(root.get("id"), id));
List<Timetable> topics = this.entityManager.createQuery(criteria) .getResultList();
return topics;

JPA OneToMany relations and performace

I have two entities: parent Customer and child Order.
Each Customer has 1,000,000 Orders for example, so it is not needed in any given time to load a Customer with all Orders but I want to have this ability to make join query on these two entities in JPA.
So because of this, I must create #OneToMany relationship for making join queries.
My question is: how to get query without making joinColumn because even in Lazy mode it is possible to load 1,000,000 objects!
I just want to get query on these object with where restrictions like native join.
If you don't want the #OneToMany relationship implicitly set in your Customer class than you don't have to. You can execute JPQL queries (in very precise manner) without the marked relationship.
Assume you have:
#Entity
public class Customer {
// all Customer-related fields WITHOUT #OneToMany relationship with Order
}
#Entity
public class Order {
#ManyToOne
private Customer owner;
}
Then if you want to get all Orders for particular Customer you can execute a simple JPQL query like that:
// Customer customer = ...
// EntityManager em = ...
String jpql = "SELECT o FROM Order o WHERE o.owner = :customer";
TypedQuery<Order> query = em.createQuery(jpql, Order.class);
query.setParameter("customer", customer);
List<Order> orders = query.getResultList();
In this way you can execute the code only when you're really sure you want to fetch Customer's orders.
I hope I've understood your problem correctly.
EclipseLink has support for QueryKeys, that allow you to define fields or relationships for querying that are not mapped. Currently there in no annotation support for query keys, but you can define them using the API and a DescriptorCustomizer.
Also you do not need the OneToMany to query on it, just use the inverse ManyToOne to query,
i.e.
Select distinct c from Customer c, Order o where o.customer = c and o.item = :item
Or,
Select distinct o.customer from Order o join o.customer c where o.customer = c and o.item = :item

Order Zend_Db_Table rowset by reference column

i know i can define relationships through _referenceMap, i know that i con join selects trough
$db->select()
But what i need is to fetch rowset in model extending Zend_Db_Table_Abstract and then order it by value of referenced column from another table.
Is there some workaround to do that?
edit:
heres is the example:
first table:
table bugs columns id, bugname, authorid
second table:
table authors columns id, authorname
I have a model Model_Bugs extends Zend_Db_Table_Abstract
I want to make something like this:
$model->fetchAll($model->select()->order('authorname ASC'))
This means, that i need to join tables and sort by a column, which is not in the model table.
thanks for help
Jan
I would add a method in Model_Bugs like so:
public function fetchBugsByAuthorname() {
$bugTable = $this;
$bugTableName = $this->info('name');
$authorsTable = new Model_Authors();
$authorsTableName = $authorsTable->info('name');
$select = $bugTable->select()
->setIntegrityCheck(false)
->from($bugTable, array('id', 'bugname', 'authorid'))
->join($authorsTableName,
"$bugTableName.authorid = $authorsTableName.id",
array("authorname"))
->order("$authorsTableName.authorname asc");
$result = $bugTable->fetchAll($select);
return $result;
}
But to do this you have to turn off ZF's table integrity checking (setIntegrityCheck(false) above), which means you won't be able to directly call save() on the resulting rows. But if it's for a read-only purpose, it will work.
If you needed to save rowsets back to the database, you may have to first select the author ID's from Model_Authors in the order you want them, and then re-order your Model_Bugs query accordingly. It's messier but it can work.

JPA criteriabuilder "IN" predicate on foreign key error: Object comparisons can only use the equal() or notEqual() operators

I want to select a list of file references from a table by looking at which users have the rights to retrieve that file. To do this I have 3 tables, a file table, an access control table, and a users table.
I am using JPA and Criteriabuilder (because there are more tables involved and I need dynamicle create the query, I am leaving out the other tables and predicates from this question for the sake of readability).
The following code works
CriteriaBuilder queryBuilder = em.getCriteriaBuilder();
CriteriaQuery<File> queryDefinition = queryBuilder.createQuery(File.class);
Root<File> FileRoot = queryDefinition.from(File.class);
List<Predicate> predicateList = new ArrayList<Predicate>();
Predicate userPredicate = FileRoot .join("FileAccesControlCollection").join("userId").get("usersId").in(loggedInUser.getUsersId());
predicateList.add(userPredicate );
queryDefinition.where(predicateArray).distinct(true);
Query q = em.createQuery(queryDefinition);
List<Files> results = (List<Files>) q.getResultList();
For the userpredicate I want to leave out the last join to the users table because the ID that I want to filter on is already present in the FileAccesControlCollection table, and a join is a computational expensive database operation.
What I tried is to do this:
Predicate userPredicate = FileRoot .join("FileAccesControlCollection").get("usersId").in(loggedInUser.getUsersId());
But I guess because the userId value in the FileAccesControlCollection entity class is a foreignkey reference to the Users class I get the following error:
Exception Description: Object comparisons can only use the equal() or notEqual() operators. Other comparisons must be done through query keys or direct attribute level comparisons.
Is there a way, using the loggedInUser entity or its Id, to filter the files by just joining the File class to the FileAccesControlCollection class and filtering on the userId foreign key? I am kind of new to JPA and using google lead me to a lot of pages but not a clear answer for something which seems to me should be possible.
So "userId" is mapped as a OneToOne? Then you could do,
get("userId").get("id").in(...)
You could also add a QueryKey in EclipseLink using a DescriptorCustomizer for the foreign key field and then use it in the query,
get("userFk").in(...)
try this:
Predicate userPredicate = FileRoot.join(FileAccesControlCollection.class).join(Users.class).get("{id field name in class Users}").in(loggedInUser.getUsersId());
good luck.