I'm having a hard time figuring out how to make effective use of query caching criteria queries on the following entity:
#Entity #Table(name = "category_configuration_values")
#Immutable
#Cacheable
#org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class CategoryConfigurationValue implements Serializable {
private static final long serialVersionUID = 3L;
private static final Logger LOGGER = LoggerFactory.getLogger(CategoryConfigurationValue.class);
#EmbeddedId
private CategoryConfigurationValuePk primaryKey;
#Column(name = "value")
private String value;
#Override
public boolean equals(Object o) { ... }
#Override
public int hashCode() { ... }
}
#Embeddable
#Cacheable
#org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
class CategoryConfigurationValuePk implements Serializable {
private static final long serialVersionUID = 5068893389269876464L;
#Column(name = "configuration_type_id")
private int configurationTypeId;
#Column(name = "category_id", columnDefinition = "smallint")
private int categoryId;
#Override
public int hashCode() { ... }
#Override
public boolean equals(Object obj) { ... }
}
The one of the criteria which is resulting in cache misses is:
Criteria criteria = getCurrentSession().createCriteria(CategoryConfigurationValue.class);
criteria.setCacheable(true);
criteria.setCacheRegion("query.AllConfigurationValuesForCategoriesAndAncestors");
criteria.add(Restrictions.in("primaryKey.categoryId", categoryIds));
List<CategoryConfigurationValue> allCategoryConfigurationValues = criteria.list();
The first time is is executed I get the 'in' query:
Hibernate: select this_.category_id as category1_4_0_, this_.configuration_type_id as configur2_4_0_, this_.value as value4_0_ from category_configuration_values this_ where this_.category_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
If I execute it another time I get a lot of the following, which to me looks like cache misses:
Hibernate: select categoryco0_.category_id as category1_4_0_, categoryco0_.configuration_type_id as configur2_4_0_, categoryco0_.value as value4_0_ from category_configuration_values categoryco0_ where categoryco0_.category_id=? and categoryco0_.configuration_type_id=?
Hibernate: select categoryco0_.category_id as category1_4_0_, categoryco0_.configuration_type_id as configur2_4_0_, categoryco0_.value as value4_0_ from category_configuration_values categoryco0_ where categoryco0_.category_id=? and categoryco0_.configuration_type_id=?
Hibernate: select categoryco0_.category_id as category1_4_0_, categoryco0_.configuration_type_id as configur2_4_0_, categoryco0_.value as value4_0_ from category_configuration_values categoryco0_ where categoryco0_.category_id=? and categoryco0_.configuration_type_id=?
Hibernate: select categoryco0_.category_id as category1_4_0_, categoryco0_.configuration_type_id as configur2_4_0_, categoryco0_.value as value4_0_ from category_configuration_values categoryco0_ where categoryco0_.category_id=? and categoryco0_.configuration_type_id=?
Hibernate: select categoryco0_.category_id as category1_4_0_, categoryco0_.configuration_type_id as configur2_4_0_, categoryco0_.value as value4_0_ from category_configuration_values categoryco0_ where categoryco0_.category_id=? and categoryco0_.configuration_type_id=?
...
What could I be missing here?
eventhough you've enabled query caching, you need to explicitly add the class CategoryConfigurationValue as cachable, then all instances of the class is marked as cachable, this would solve your problem..
Anantha Sharma
Related
For some reason with this setup, when saving the transaction with a nested ticket. It will create both and then connect the two. However when I use the transaction repository to find the transaction it will have an attached ticket however when I use the ticket repository and find the ticket, it doesn't have the attached transaction. I generated this relationship with jhipster jdl, not sure what is going wrong here.
Transaction.java
...
#JsonIgnoreProperties(value = { "person", "event", "transaction", "nameTags" }, allowSetters = true)
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(unique = true)
private Ticket tickets;
public Ticket getTickets() {
return this.tickets;
}
public Transaction tickets(Ticket ticket) {
this.setTickets(ticket);
return this;
}
public void setTickets(Ticket ticket) {
this.tickets = ticket;
}
...
Ticket.java
...
#JsonIgnoreProperties(value = { "tickets", "membershipLevel", "person", "event" }, allowSetters = true)
#OneToOne(mappedBy = "tickets")
private Transaction transaction;
public Transaction getTransaction() {
return this.transaction;
}
public Ticket transaction(Transaction transaction) {
this.setTransaction(transaction);
return this;
}
public void setTransaction(Transaction transaction) {
if (this.transaction != null) {
this.transaction.setTickets(null);
}
if (transaction != null) {
transaction.setTickets(this);
}
this.transaction = transaction;
}
...
Edit:
Here is the generated SQL output, it is showing here just a normal select wihtout joins from both but transaction has the ticket_id in the transaction table while ticket is doing the same but has no reference and would need to do a join but is not.
Hibernate: insert into ticket (cost_per_ticket, count, event_id, person_id, picked_up, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into transaction (cost_sub_items_purchased, date, donation, event_id, event_donation, generic_sub_items_purchased, membership_level_id, notes, number_of_memberships, person_id, tickets_id, total_amount, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select transactio0_.id as id1_23_, transactio0_.cost_sub_items_purchased as cost_sub2_23_, transactio0_.date as date3_23_, transactio0_.donation as donation4_23_, transactio0_.event_id as event_i10_23_, transactio0_.event_donation as event_do5_23_, transactio0_.generic_sub_items_purchased as generic_6_23_, transactio0_.membership_level_id as members11_23_, transactio0_.notes as notes7_23_, transactio0_.number_of_memberships as number_o8_23_, transactio0_.person_id as person_12_23_, transactio0_.tickets_id as tickets13_23_, transactio0_.total_amount as total_am9_23_ from transaction transactio0_
Hibernate: select ticket0_.id as id1_22_, ticket0_.cost_per_ticket as cost_per2_22_, ticket0_.count as count3_22_, ticket0_.event_id as event_id5_22_, ticket0_.person_id as person_i6_22_, ticket0_.picked_up as picked_u4_22_ from ticket ticket0_
I am trying to insert data of user actions using Spring JPA Single table type inheritance. Below are my classes:
RmlAction.java - The super class
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "entityType")
#Getter
#Setter
#NoArgsConstructor
#Table(name = "rml_actions")
public abstract class RmlAction extends RmlBase {
//attributes
}
RmlProjectAction.java
#Entity
#Getter
#Setter
#DiscriminatorValue(value = "PROJECT")
#NoArgsConstructor
public class RmlProjectAction extends RmlAction {
//constructor
}
RmlEfsAction.java
#Entity
#Getter
#Setter
#DiscriminatorValue(value = "EFS")
#NoArgsConstructor
public class RmlEfsAction extends RmlAction {
//constructor
}
When I try to insert data using ActionRepository, it gives the below error
Hibernate: insert into rml_user (active, creation_date, last_modified_date, object_version, activated, directory_role, efs_id, efs_stack_id, email, login_id, organization, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into rml_efs_action (active, creation_date, last_modified_date, object_version, action_params, action_status, action_type, entity_id, job_id, message, published, user, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2020-02-03 15:53:43,767 WARN [http-nio-5000-exec-1] org.hibernate.engine.jdbc.spi.SqlExceptionHelper: SQL Error: 1146, SQLState: 42S02
2020-02-03 15:53:43,768 ERROR [http-nio-5000-exec-1] org.hibernate.engine.jdbc.spi.SqlExceptionHelper: Table 'rmldb.rml_efs_action' doesn't exist
Notice here that it is trying to insert into rml_efs_action table and I don't understand the reason. I tried multiple things but nothing works.
I have the following Entity Relations:
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Data
#Entity
public class BatchProcessRecord implements Serializable, Cloneable {
...
#ManyToOne
#JoinColumn(name = "batch_process_id")
private BatchProcess batchProcess;
}
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Data
#Entity
public class BatchProcess implements Serializable, Cloneable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "batchProcess")
private List<BatchProcessRecord> records;
}
And the following code that saves the entities:
// Create batch process
BatchProcess batchProcess = BatchProcess.builder()
....
.records(records)
.build();
// Save entity
batchProcessRepository.save(batchProcess);
In the console, it generates the inserts as expected (with 2 children), but without filling batch_process_id (JoinColumn).
What is happening?
Console:
Hibernate: insert into batch_process (batch_end_date, batch_entries_count, batch_entries_with_issues, batch_name, batch_start_date, report_file_download_date, report_file_name, result_file_name, result_file_upload_date, status) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into batch_process_record (address_number, batch_process_id, city, first_name, full_street_address, last_name, maternal_name, post_directional, pre_directional, reference_number, ssn, state, street_type, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into batch_process_record (address_number, batch_process_id, city, first_name, full_street_address, last_name, maternal_name, post_directional, pre_directional, reference_number, ssn, state, street_type, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2
Repository:
public interface BatchProcessRepository extends
JpaRepository<BatchProcess, Long> {
}
I have a problem when trying to persist new entities. I'm using Eclipselink 2.4.2 as entity manager. My BaseDao class in the store method flushes and refreshes entity after persisting it as new (persist->flush->refresh). All is happening in a single transaction.
My entities look like this (the part I'm concerned about):
TrustEntity {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "trust", cascade = {CascadeType.ALL})
#PrivateOwned
private List<TrustIncentiveRateEntity> trustIncentiveRates;
}
TrustIncentiveRateEntity {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "TRUST_ID", nullable = false)
private TrustEntity trust;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "trustIncentiveRate", cascade = {CascadeType.ALL})
#PrivateOwned
private List<TrustIncentiveRateValueEntity> trustIncentiveRateValues;
}
TrustIncentiveRateValueEntity {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "TRUST_INCENTIVE_RATE_ID", nullable = false)
private TrustIncentiveRateEntity trustIncentiveRate;
}
I'm creating a new Trust entity, instantiate a TrustIncentiveRateEntity list, create one new element in it, instantiate a TrustIncentiveRateEntity and create one new element in it.
During debugging I could see that all the references, in both ways, are correct.
Now, when I try to persist this here is what happens:
Log from server:
FINE: SELECT SEQ_TRUST.NEXTVAL FROM DUAL
FINE: SELECT SEQ_TRUST_INCENTIVE_RATE.NEXTVAL FROM DUAL
FINE: SELECT SEQ_TRUST_INCENTIVE_RATE_VALUE.NEXTVAL FROM DUAL
FINE: INSERT INTO TRUST (TRUST_ID, ACTION_DATE, ACTION_USER_ID, IS_ACTIVE, CREATION_DATE, CREATION_USER_ID, IS_INCENTIVE_ACTIVE, IS_NO_CREDIT_LIMIT, PROCESS_CURRENT_STATUS, REMARKS, STATUS_INCENTIVE, TRUST_CODE, TRUST_NAME, TRUST_TYPE, UPDATE_DATE, UPDATE_USER_ID, VERSION_OPT_LOCK, STRUCTURAL_ORG_UNIT_SALES_ID, STRUCTURAL_ORG_UNIT_ID, USER_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [38007, 2013-04-26 09:46:31.582, 1003186, true, 2013-04-26 07:46:34.659, 1003186, true, false, OPEN, null, OPEN, 100058, 741963852, T, null, null, 1, 387, 387, 1003186]
FINE: INSERT INTO TRUST_INCENTIVE_RATE (TRUST_INCENTIVE_RATE_ID, CREATION_DATE, CREATION_USER_ID, EQUIPMENT_SIZE, EXTENDED_EQ_GROUP_ID, RATE_BASIS, UPDATE_DATE, UPDATE_USER_ID, VERSION_OPT_LOCK, TRADE_ID, TRUST_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [15001, 2013-04-26 07:46:39.862, 1003186, 20, 2, B, null, null, 1, 144001, 38007]
FINE: INSERT INTO TRUST_INCENTIVE_RATE_VALUE (TRUST_INCENTIVE_RATE_VALUE_ID, CREATION_DATE, CREATION_USER_ID, EFFECTIVE_DATE, EXPIRY_DATE, INCENTIVE, STATUS, UPDATE_DATE, UPDATE_USER_ID, VERSION_OPT_LOCK, CURRENCY_CODE, TRUST_INCENTIVE_RATE_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [14007, 2013-04-26 07:46:39.955, 1003186, 2013-04-26 00:00:00.0, 9999-12-31 00:00:00.0, 12, OPEN, null, null, 1, USD, 15001]
FINE: SELECT TRUST_ID, ACTION_DATE, ACTION_USER_ID, IS_ACTIVE, CREATION_DATE, CREATION_USER_ID, IS_INCENTIVE_ACTIVE, IS_NO_CREDIT_LIMIT, PROCESS_CURRENT_STATUS, REMARKS, STATUS_INCENTIVE, TRUST_CODE, TRUST_NAME, TRUST_TYPE, UPDATE_DATE, UPDATE_USER_ID, VERSION_OPT_LOCK, STRUCTURAL_ORG_UNIT_SALES_ID, STRUCTURAL_ORG_UNIT_ID, USER_ID FROM TRUST WHERE (TRUST_ID = ?)
bind => [38007]
FINE: SELECT TRUST_INCENTIVE_RATE_ID, CREATION_DATE, CREATION_USER_ID, EQUIPMENT_SIZE, EXTENDED_EQ_GROUP_ID, RATE_BASIS, UPDATE_DATE, UPDATE_USER_ID, VERSION_OPT_LOCK, TRADE_ID, TRUST_ID FROM TRUST_INCENTIVE_RATE WHERE (TRUST_ID = ?)
bind => [38007]
FINE: SELECT TRUST_INCENTIVE_RATE_VALUE_ID, CREATION_DATE, CREATION_USER_ID, EFFECTIVE_DATE, EXPIRY_DATE, INCENTIVE, STATUS, UPDATE_DATE, UPDATE_USER_ID, VERSION_OPT_LOCK, CURRENCY_CODE, TRUST_INCENTIVE_RATE_ID FROM TRUST_INCENTIVE_RATE_VALUE WHERE (TRUST_INCENTIVE_RATE_ID = ?)
bind => [15001]
So far so good, but when the transaction is commited by EntityManager I get the following exception:
WARNING: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: my.package.entity.TrustIncentiveRateEntity#1fa1df7.
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.discoverUnregisteredNewObjects(RepeatableWriteUnitOfWork.java:303)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:706)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1498)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3151)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:345)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:158)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:435)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5136)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at $Proxy241.save(Unknown Source)
Which for me seems strange, like the EM tries to actually store TrustIncentiveRateValueEntity before TrustIncentiveRateEntity and can't see TrustIncentiveRateEntity.
After looking at similar threads I've added CascadeType.PERSIST to the #ManyToOne annotation over trustIncentiveRate field in TrustIncentiveRateValueEntity class. After that the situation looks like this: EM inserts the entities like before AND THEN it gets nextval from SEQ_TRUST_INCENTIVE_RATE and tries to insert TrustIncentiveRateValueEntity again (with the new id, but the rest of the field values remain the same). It results in constrain violation, as I have a unique constrain on cross-section of some of this table columns. Exception, transaction rolled back, I am still sad.
My store method in the BaseDao class:
#TransactionAttribute(TransactionAttributeType.MANDATORY)
public T_ENTITY store(T_ENTITY entity) {
if (!entity.isNewlyCreated()) {
T_ENTITY mergedEntity = em.merge(entity);
flush();
return mergedEntity;
} else {
try {
em.persist(entity);
flush();
refresh();
} catch (RuntimeException exc) {
entity.resetPersistentFlag();
throw exc;
}
return entity;
}
}
But calling the em.persist(entity) directly, without flush/refresh causes the same problem.
The logic of the service call:
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public TrustEntity save(TrustEntity dto) {
TrustEntity trust = trustDao.store(trust);
workflowConversation.triggerWorkflow(); // doesn't do anything to any of the entities when they are freshly created
return trust;
}
Anybody could help me in identifying what could be wrong with this?
You cannot have a OneToMany that uses both a mappedby, making it bidirectional, and a joincolumn marking it as unidirectional. They conflict and are causing you issues.
When you mark a relationship as mappedby, you specify that all information and control of the relationship is on the other side - that includes the joincolumn info. try:
TrustEntity {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "trust", cascade = {CascadeType.ALL})
#PrivateOwned
private List<TrustIncentiveRateEntity> trustIncentiveRates;
}
TrustIncentiveRateEntity {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "TRUST_ID", nullable = false)
private TrustEntity trust;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "trustIncentiveRate", cascade = {CascadeType.ALL})
#PrivateOwned
private List<TrustIncentiveRateValueEntity> trustIncentiveRateValues;
}
I have the following code and the insertion is being done but the query in the query() is not printing the println that its suppose to.
package com;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import roseindia.tutorial.hibernate.Insurance;
import com.Employee;
public class EmployeeEx
{
public static void main(String[] args)
{
Session session = null;
try
{
Transaction transaction = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
File f=new File("c:/Class/Employee1.txt") ;
Scanner scan=new Scanner(f);
transaction = session.beginTransaction();
while(scan.hasNext())
{
Employee em = new Employee();
String line=scan.nextLine();
String empArray[]=line.split(" ");
em.setId(Integer.parseInt(empArray[0]));
em.setName(empArray[1]);
em.setSalary(Double.parseDouble(empArray[2]));
em.setManager(empArray[3]);
session.save(em);
transaction.commit();
}
query();//calling the query method
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.flush();
session.close();
}
}
public static void query()
{
Session session = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.like("manager", "Anurag"));
criteria.add(Restrictions.gt("salary", 1000));
List emp = criteria.list();
for(Iterator it = emp.iterator();it.hasNext();)
{
Employee em = (Employee) it.next();
System.out.println("Id: " +em.getId());;
System.out.println("Name: " +em.getName());
System.out.println("Salary: " +em.getSalary());
System.out.println("Manager: " +em.getManager());
}
session.close();
}
}
This is what is shown on the console:(The insertion is working fine)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: select this_.ID as ID0_, this_.NAME as NAME7_0_, this_.SALARY as SALARY7_0_, this_.MANAGER as MANAGER7_0_ from EMPLOYEE1 this_ where this_.MANAGER like ? and this_.SALARY>? java.lang.Integer
The query() method is not being executed because you are not calling it.
Anyway, you can't call it from main() unless you make it static:
public static void query()
Only the main() method will be executed when you run a class, so after you have added static to the method signature of query(), add this line somewhere to your main() method:
query();
If you are calling the query() method and it still doesn't print anything, then it means that your emp list is empty. Check your database if you have any record matching the restrictions of your query. If you do then check the contents of list emp.