Using sub queries - java

I am trying to access a data in a table using a sub query.
The table 1 contains a foreign key to table 2 , which means i can use that key to access the data in table 2.
My problem is after i return the array list from the below shown method , the arraylist is null.
This is what i have done:
LogEntry logBookDates;
List<LogEntry> bookList =new ArrayList();
try{
PreparedStatement getSummaryStmt=con.prepareStatement("SELECT * FROM LOGENTRYTABLE WHERE DIARYCODE =(SELECT Diarycode FROM LOGBOOKTABLE WHERE STUDENTUSERNAME=? OR SUPERVISORUSERNAME=? AND PROJECT_APPROVE_STATUS=?)");
//the above statment is the sub query which i have created, i get the diary code from log book table and then access the log entry table.
getSummaryStmt.setString(1,userName);
getSummaryStmt.setString(2,userName);
getSummaryStmt.setString(3,"Accepted");
ResultSet rs=getSummaryStmt.executeQuery();
while(rs.next())
{
logBookDates=new LogEntry(rs.getString("STUDENTUSERNAME"),rs.getString("SupervisorUsername"),rs.getString("projecttitle"),rs.getString("projectDescription"),rs.getDate("startDate"),rs.getDate("enddate"),rs.getString("project_approve_status"),rs.getString("diarycode"),rs.getString("projectcode"),rs.getInt("Index"),rs.getString("log_Entry"),rs.getDate("logentry_date"),rs.getString("supervisor_comment"),rs.getString("project_progress"));
bookList.add(logBookDates);
}
}catch(Exception e){}
return bookList;
}
I have not used sub queries before and this is the first time am using them.
What seems to be the problem here ?
Thank you for your time.
Edit : Sample data of logbook table
Sample Data of logentry table
Expected output:
I don't have a screen shot of that but what i need is just to iterate through the arraylist which will be returned from the above method.

Here is the problem, the LOGENTRYTABLE table doesn't contain a column with STUDENTUSERNAME, SupervisorUsername, projecttitle, projectDescription, startDate, etc...
rs.getString("STUDENTUSERNAME"), rs.getString("SupervisorUsername"), etc...
probably, you need JOIN query
"SELECT * FROM LOGENTRYTABLE LT
INNER JOIN LOGBOOKTABLE LB ON LT.DIARYCODE=LB.DIARYCODE
WHERE LT.DIARYCODE =
(SELECT DIARYCODE FROM LOGBOOKTABLE
WHERE (STUDENTUSERNAME=? OR SUPERVISORUSERNAME=?)
AND PROJECT_APPROVE_STATUS=?)"

Related

Append two hibernate query list and store in third query list

The first table contain list from Database and store in qry and the second table also contain list from Database and store in qry1 then how to append these list in the third qry2.
Query qry = getSession().createQuery("select * from table1");
Query qry1 = getSession().createQuery("select * from table2");
Query qry2 = dry+qry1;
Why don't you simple do
List<Object> result = new ArrayList<Object>();
result.addAll(qry.list());
result.addAll(qry1.list());
You have to take a List of Object's since the both Pojo's are different from table1 to table2.

Pagination with ordered data with hibernate

Using hql in hibernate we can do pagination on a table data using below, but below will return first 5 data records in the table.
String SQL_QUERY = "FROM Order order";
Query query = session.createQuery(SQL_QUERY);
query.setFirstResult(1);
query.setMaxResults(5);
But how can i do the pagination on a ordered data on a table for example an ordered data set by a order_id ?
Not sure what you're asking, but just add order by clause in your query, and calculate first result based on page. Something like this
String HQL_QUERY = "FROM Order o order by o.id";
Query query = session.createQuery(HQL_QUERY);
// page size
query.setMaxResults(5);
// page 1
query.setFirstResult(1);
// page 2
query.setFirstResult(6);
...

Hibernate result list cast to get rows

Hello I had problem with iterate Hibernate ResultList
I had followed query that I got from external class:
queryContent = "select distinct c.identity, c.number, c.status, ctr.name, aab.paymentConditions.currency from AgreementStateBean ast join ast.currentAgreement aab join conagr.contract c where c.agreementStateId = ? and con.mainContractor = true ? "
And I must sum whole aab.paymentConditions.currency, check numbers of statutes and names.
I want to do this by iterate list of results:
Query q = session.createQuery(queryContent);
List result = q.list();
Long wholeCurrency, numberOfStatutes;
for(Object res : result){
//wholeCurrency += res.getColumnName?
}
My question is how to cast res Object to have possibility to get concrete column values? I had read about create map inside hibernate query but I don't know it is good practice to modyfied query string by adding
"new map(" prefix and then ")"
before from sql statement
Solution:
After All I decided to use map in my query. I modified my external query by adding hibernate map statement by replacing select by 'select new map(' and from by ') from'.
Additional thing is to add 'as' statement with name of key because without them column keys are integer.
So after all my query looks like follow:
"select new map( distinct c.identity, c.number, c.status as status, ctr.name as name, aab.paymentConditions.currency as currency ) from AgreementStateBean ast join ast.currentAgreement aab join conagr.contract c where c.agreementStateId = ? and con.mainContractor = true ? "
That was the most siutable solution for me, I tried with 'NEW com.example.MyClass' as Kostja suggested but in my case I didn't have control for incoming query so I can not rely on pernament constructor.
new List( select...
Is also interest but it also didn't tell me on with position I have my field that give me information.
If I understand correctly, you want to have a typed representation of your result without it being an entity itself. For this, you can use constructor queries:
"SELECT NEW com.example.MyClass( e.name, e.data) FROM Entity e"
MyClass has to have a matching constructor. Full qualification (com.example) is not mandatory AFAIK.
If you are using this query often, creating a view in the DB may be a good idea. You can map a view to an entity just as if it were a regular table, but please note that you cannot store changes to you data over a mapped view.
EDIT: Turns out, mapping to an unspecified Map is alright with Hibernate:
select new map( mother as mother, offspr as offspr, mate as mate )
As per http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch11.html#ql-select-clause
you can use
queryContent = "select new list(distinct c.identity, c.number, c.status, ctr.name, aab.paymentConditions.currency) from AgreementStateBean ast join ast.currentAgreement aab join conagr.contract c where c.agreementStateId = ? and con.mainContractor = true ? "
And you get List<List> as result.

Select data from two tables using SQL

I have two tables linked by another table like this:
ROLES(RoleID, RoleName)
EMPLOYEES(EmployeeID, E_Name, Address)
ROLE_EMPLOYEES(RoleID#,EmployeeID#).
I want a query that retrieves all from EMPLOYEES and RoleID from ROLES and displays on Java form.
I have tried this but does not work:
rs=st.executeQuery("SELECT EMPLOYEES.*, ROLES.* FROM EMPLOYEES JOIN ROLES");
while(rs.next()){
//MOVE THE CURSOR TO THE FIRST RECORD AND GET DATA
int employeeid=rs.getInt("EmployeeID");
String id=Integer.toString(employeeid);
String name=rs.getString("E_Name");
String addr=rs.getString("Address");
String s = rs.getString("RoleID");
jComboBox1.addItem(s.trim());
//DISPLAY THE FIRST RECORD IN THE TEXT FIELD
txtEmpNumber.setText(id);
txtEmpName.setText(name);
txtEmpAddress.setText(addr);
jComboBox1.setSelectedItem(s);
}
You may try this:
SELECT
EM.*, RL.*
FROM
EMPLOYEES EM
INNER JOIN
ROLE_EMPLOYEES REM ON REM.EmployeeID = EM.EmployeeID
INNER JOIN
ROLES RL ON RL.RoleID = REM.RoleID
Just by writing the keyword JOIN the db-engine does not know in which way it should join the data of the tables; unless you want to retrieve a cartesian product (that's not your case), you need to explicitly set the criteria by using the ON clause.

Searching Multiple Tables and Returning/Mapping a Dynamic Result Set

I have a mySql schema named Contacts that contains 4 tables: Contacts, Phone, Email, and Addresses. The Contacts table contains basic information about a person such as an id number, first name, and last name. The other tables all contain a foreign key that links it to the Contacts table so for example, John Doe in the Contacts table can have multiple phone numbers in the Phones table that are all searchable by using John Doe's id number.
My question is how do I query this schema and return all data for a single (or multiple) users. Can it be done with one SQL statement, or do I need to contact the database for each individual table based on the fact that the amount of results returned will not match for each row returned from the Contacts table. For example, I have some basic search functionality that searches the Contacts table for one or more rows based on search criteria:
public class ContactsListDAO {
//Constants
private static final String SQL_FIND_BY_SEARCH_CRITERIA = "SELECT * FROM Contacts.Contacts WHERE Id LIKE :searchString OR FirstName LIKE :searchString OR LastName LIKE :searchString";
//Variables
private DAOFactory daoFactory;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
//Constructors
public ContactsListDAO(DAOFactory daoFactory) {
this.daoFactory = daoFactory;
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(daoFactory.getDataSource());
}
public List<Contact> findSearchResults(String searchCriteria) {
Map<String, String> namedParameters = Collections.singletonMap("searchString", searchCriteria);
RowMapper<Contact> mapper = new RowMapper<Contact>() {
#Override
public Contact mapRow(ResultSet resultSet, int row) throws SQLException {
Contact contact = new Contact(
resultSet.getInt("Id"),
resultSet.getString("FirstName"),
resultSet.getString("LastName")
);
return contact;
}
};
return namedParameterJdbcTemplate.query(SQL_FIND_BY_SEARCH_CRITERIA, namedParameters, mapper);
}
}
I am using spring to query and map the results back to a Contact bean. How would I go about modifying this SQL statement and mapping functionality to search the contacts table, get the data for each row and then based on the id of each returned row, also query the phone, email, and address tables and then map those to a List object stored in the bean? The problem is that row 1's id might find 8 phone numbers rows that match the id, but row 2's id might only find 3 phone numbers. How is this going to be stored in a ResultSet? Or will I have to query the Contacts table first and then perform a separate query for each other table (for each row returned from the first) and add that data to the bean case by case? If the first query returns 100 results, and I have to perform a query for each of those on 3 tables, I am looking at 301 trips to the database and back.
Is it possible to use one query and just return 1 result from each of the phone, email, address tables for each result found in the Contacts table? Maybe I can add a primary column or something so it only returns 1 result and then if the user clicks something to request more information about the result it can perform the other queries and gather all the info about that user.
The query i've come up with uses LEFT JOIN to search the tables:
SELECT * FROM Contacts.Contacts LEFT JOIN Contacts.Phone ON Contacts.Id = Phone.ContactId AND Phone.Primary = 1 LEFT JOIN Contacts.Email ON Contacts.Id = Email.ContactId AND Email.Primary = 1 WHERE Contacts.Id LIKE :searchString OR Contacts.FirstName LIKE :searchString OR Contacts.LastName LIKE :searchString AND Contacts.OrganizationId = :organizationId
I created a column in the Phone, Email, and Address database called Primary that contains a boolean so that on my initial query I will only return 1 result for each Contact in the database. So far this is doing what I need. Not sure if it the proper way to go about something like this?

Categories

Resources