In my entity I have this field
#ElementCollection
#CollectionTable
#MapKeyColumn(name = "SERVER_ID")
#Column(name = "IS_SYNC")
private Map<String, Boolean> serverSyncs = new HashMap<>();
I'm trying to get all entities of my table that do not have an entry with the key equals to "serverId" (passed as parameter in my function) or that have an entry but the value is false.
This is what I've done for now
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery = builder.createQuery(clazz);
Root<T> root = criteriaQuery.from(clazz);
MapJoin<T, String, Boolean> mapRoot = root.joinMap("serverSyncs");
List<T> result = session.createQuery(
criteriaQuery.where(
builder.or(
mapRoot.isNull(),
builder.not(mapRoot.key().in(serverId)),
builder.and(
mapRoot.key().in(serverId),
mapRoot.value().in(false)
)
)
)
).list();
The thing is I get this error on my query
Could not locate CollectionPersister for role : ca.tecsar.core.model.AbstractServerEntity.serverSyncs
Question is : how can I achieve what I want with JPA 2.0 Criteria?
Example of what I need to retrieve
id|SERVER_ID|IS_SYNC
1|0000000001|true
1|0000000002|false
2|0000000003|false
If I ask for SERVER_ID = 3,I should get entity 1 and 2
If I ask for SERVER_ID = 2,I should get entity 1
If I ask for SERVER_ID = 1,I should get nothing
So I couldn't do it with JPA 2 Criteria but I've succeeded with a SQL Query. I have a table named PUNCH and the map table is PUNCH_SERVERSYNCS.
SELECT p.PUNCHID
FROM PUNCH p
LEFT JOIN PUNCH_SERVERSYNCS pss
ON p.PUNCHID = pss.PUNCH_PUNCHID
WHERE (pss.IS_SYNC = false AND pss.SERVER_ID = 'Server2')
OR NOT EXISTS (SELECT p.PUNCHID FROM PUNCH_SERVERSYNCS pss2 WHERE
pss2.PUNCH_PUNCHID = p.PUNCHID AND pss2.SERVER_ID = 'Server2')
GROUP BY p.PUNCHID
Related
I have tables like below
import sqlalchemy as sa
class A(Base):
id = sa.Column(sa.Integer)
name = sa.Column(sa.String)
class B(Base):
id = sa.Column(sa.Integer)
a_id = sa.Column(sa.Integer)
and has query:
# Basic query
query = sa.select(B).join(A, A.id == B.a_id)
result = await session.execute(query)
results = result.scalars().all()
How should I change to get desired result?
query = sa.select(B).join(A, A.id == B.a_id)
result = session.execute(query)
results = result.scalars().all()
# Problem
# SOME_KEY should be indicated in query as loading column
# SOME_KEY's type should be A class
# I want below thing
results[0].SOME_KEY.name # it should give joined `A` entity's property value
I have read documentation, have seen loading techniques, but could not find solution , it is mostly for relations.
Arbitrary query with multiple objects per result
with Session(engine) as session:
for (b, a) in session.execute(select(B, A).join(A, B.a_id == B.id)).all():
print (b, a)
Relationship without ForeignKey
from sqlalchemy.orm import Session, declarative_base, aliased, relationship, remote, foreign
class A(Base):
__tablename__ = 'a_table'
id = Column(Integer, primary_key=True)
name = Column(String)
b_list = relationship('B', primaryjoin="remote(A.id) == foreign(B.a_id)", back_populates='a')
class B(Base):
__tablename__ = 'b_table'
id = Column(Integer, primary_key=True)
a_id = Column(Integer)
a = relationship('A', primaryjoin="remote(A.id) == foreign(B.a_id)", back_populates='b_list')
with Session(engine) as session:
for (b,) in session.execute(select(B).join(B.a)).all():
print (b, b.a_id, b.a, b.a.id, b in b.a.b_list)
I can't get the syntax here; are there some more extensive examples for POCO-SQLite ?
I am getting a Poco::exception,
sendErrorResponse HTTP_INTERNAL_SERVER_ERROR
Poco::Data::SQLite::Connector::registerConnector();
// create a new session
Session updsession("SQLite", managers);
facilities UnitFacility;
Statement updateRecord(updsession);
updsession << "UPDATE facilities SET name = nameString, address = addressString, phone = phoneString WHERE facilityNumber = 3;";
updateRecord.execute();
//Updated: Simplified With or without [] still no go.
Poco::Data::SQLite::Connector::registerConnector();
Session updsession("SQLite", managers);
Statement updateRecord(updsession);
updsession << "UPDATE facilities SET Name = 'Frank' WHERE [FacilityNumber = 1];",now;
updateRecord.execute();
Both SQL queries are invalid.
Original Query:
UPDATE facilities SET name = nameString, address = addressString, phone = phoneString WHERE facilityNumber = 3
Result:
no such column: nameString: UPDATE facilities SET name = nameString, address = addressString, phone = phoneString WHERE facilityNumber = 3
Fixed query:
UPDATE facilities SET name = 'nameString', address = 'addressString', phone = 'phoneString' WHERE facilityNumber = 3
Result:
Query executed successfully: UPDATE facilities SET name = 'nameString', address = 'addressString', phone = 'phoneString' WHERE facilityNumber = 3 (took 0ms, 1 rows affected)
Original query:
UPDATE facilities SET Name = 'Frank' WHERE [FacilityNumber = 1]
Result:
no such column: FacilityNumber = 1: UPDATE facilities SET Name = 'Frank' WHERE [FacilityNumber = 1]
Fixed query:
UPDATE facilities SET Name = 'Frank' WHERE FacilityNumber = 1
Result:
Query executed successfully: UPDATE facilities SET Name = 'Frank' WHERE FacilityNumber = 1 (took 0ms, 1 rows affected)
It is not clear what does this question have to do with HTTP.
So I have a root model that looks like this:
class Contact(ndb.Model):
first_name= ndb.StringProperty()
last_name= ndb.StringProperty()
age = ndb.IntegerProperty()
and a child model that looks like this:
class Address(ndb.Model)
address_type=ndb.StringProperty(choices=['Home','Office','School'],default='Home')
street = ndb.StringProperty()
city = ndb.StringProperty()
state = ndb.StringProperty()
I want to be able to perform a query similar to this:
Select first_name, last_name, street, city, state WHERE contact.age > 25 and address.city = 'Miami' and address_type = 'School'
I know I can perform searches more easily if I were to setup the addresses as a structured property within the contact model, but I don't like using Structured Properties because they don't have their own keys, thus making entity maintenance more challenging.
I tried doing a search for contacts first and then feeding the resulting keys into a WHERE IN clause but it didn't work, example:
query1 = Contact.query(Contact.age>25).iter(keys_only = True)
query2 = Address.query(Address.city=='Miami', Address.address_type=='School',Address.ancestor.IN(query1))
Any ideas as to how to go about this would be appreciated.
OK so it looks like my original idea of filtering one query by passing in the keys of another will work. The problem is that you can't perform a WHERE-IN clause against an ancestor property so you have to store the parent key as a standard ndb.KeyProperty() inside of the child entity, then perform the WHERE-IN clause against that KeyProperty field.
Here's an example that will work directly from the interactive console in the Appengine SDK:
from google.appengine.ext import ndb
class Contact(ndb.Model):
first_name= ndb.StringProperty()
last_name= ndb.StringProperty()
age = ndb.IntegerProperty()
class Address(ndb.Model):
address_type=ndb.StringProperty(choices=['Home','Office','School'],default='Home')
street = ndb.StringProperty()
city = ndb.StringProperty()
state = ndb.StringProperty()
contact = ndb.KeyProperty()
# Contact 1
contact1 = Contact(first_name='Homer', last_name='Simpson', age=45)
contact1_result = contact1.put()
contact1_address1 = Address(address_type='Home',street='742 Evergreen Terrace', city='Springfield', state='Illinois', contact=contact1_result, parent=contact1_result)
contact1_address1.put()
contact1_address2 = Address(address_type='Office',street=' 1 Industry Row', city='Springfield', state='Illinois', contact=contact1_result, parent=contact1_result)
contact1_address2.put()
# Contact 2
contact2 = Contact(first_name='Peter', last_name='Griffan', age=42)
contact2_result = contact2.put()
contact2_address1 = Address(address_type='Home',street='31 Spooner Street', city='Quahog', state='Rhode Island', contact=contact2_result, parent=contact2_result)
contact2_address1.put()
# This gets the keys of all the contacts that are over the age of 25
qry1 = Contact.query(Contact.age>25).fetch(keys_only=True)
# This query gets all addresses of type 'Home' where the contacts are in the result set of qry1
qry2 = Address.query(Address.address_type=='Home').filter(Address.contact.IN(qry1))
for item in qry2:
print 'Contact: %s,%s,%s,%s'% (item.contact.get().first_name, item.contact.get().last_name, item.address_type, item.street)
This will render a result that looks kinda like this:
Contact: Peter,Griffan,Home,31 Spooner Street
Contact: Homer,Simpson,Home,742 Evergreen Terrace
Can you use an Ancestor query?
query1 = Contact.query(Contact.age>25).iter(keys_only = True)
for contact in query1:
query2 = Address.query(Address.city=='Miami',
Address.address_type=='School',
ancestor=contact)
If that's not efficient enough, how about filtering the addresses?
query1 = Contact.query(Contact.age>25).iter(keys_only = True)
contacts = set(query1)
query2 = Address.query(Address.city=='Miami', Address.address_type=='School')
addresses = [address for address in query2 if address.key.parent() in contacts]
SELECT Inventory_Stock.id, Inventory_Stock.quantity, SUM(InventoryUsage.quantity)
,Inventory_Stock.quantity - SUM(InventoryUsage.quantity) AS Stock
FROM Inventory_Stock LEFT JOIN InventoryUsage ON Inventory_Stock.id = InventoryUsage.InventoryStock_id
WHERE Inventory_Stock.id = 26 OR
Inventory_Stock.id = 27
GROUP BY Inventory_Stock.id
ORDER BY Stock Asc
How can I write the above code in Symfony2, I want to write it as raw query
Also I am using PageFanta for pagination.. so the result from the above query will go to pagination.
Relations are :
Product ( 1 - 1) InventoryStock
InventoryStock ( 1 - n ) InventoryUsage
If it isn't a problem get all records to array. And use ArrayAdapter:
$adapter = new ArrayAdapter($array);
$pagerfanta = new Pagerfanta($adapter);
If the count of the records is too big. Write your own adapter for pagerfanta
I am collecting some data from database using var query and storing it in an integer. Below is the code:
var query1 = from meet_emp in db.Meet_Emps
where meet_emp.Employee_ID == empid
select meet_emp.Meeting_ID;
int meetNum = query1.First();
Here query1 contains multiple meeting ids. I wish to store all id's into an int variable or int array as I would be using each meeting id later into another query. With syntax "int meetNum = query1.First()", I get only the first meeting id.
How do I get all the meeting id's
You can leave the data just as it is in variable query1, then join it later with your final query that uses that list:
from blah in db.Stuff
join query1 on query1.Meeting_ID equals blah.Meeting_ID
select ...;
Just change to ToList then you will have a list of IDs
var query1 = from meet_emp in db.Meet_Emps
where meet_emp.Employee_ID == empid
select meet_emp.Meeting_ID;
var meetNum = query1.ToList();