Same Query Gives Different Output In MSSQL And Hibernate 3 - java

Users
Userid
userName
password
status
Issue
IssueNum
issueDescription
status
creationdate
IssueAssigned
issueNumber
issueAssignedTo
issueAssignedBy
comments
In my primefaces datatable I am fetching these value using following query
SELECT I.issue_number, I.issue_describtion, U.first_name,US.first_name
FROM ISSUES I
LEFT JOIN ISSUE_ASSIGNED IA
ON I.issue_number = IA.Issue_number
LEFT JOIN USERS U
ON U.id = IA.assigned_to_user_id
LEFT JOIN USERS US
ON US.id = IA.assigned_by_user_id
The Admin who is also a user assigns issue to another user
In MSSQL this above query works fine gives me proper record for U.firstName and US.FirstName as they are different user.
query in MSSQL returns
PER-1675 Perform - Evaluation Form Export does not pull any data in Legacy Export Tool (Due 8/14) Ameh Sandip
PER-2048 Calculation of scores fails when the lower/upper bound value of a calculation text result is a Ameh Sandip
But in Hibernate for the same query both firstName and US.firstName gives same result
code
#Override
public List<Object> getIssueListForAssigingIssue (){
List<Object> allIssueList = getHibernateTemplate()
.getSessionFactory()
.getCurrentSession().createSQLQuery("SELECT I.issue_number, I.issue_describtion, IT.issue_type,U.first_name ,US.first_name "
+ "FROM ISSUES I "
+ "LEFT JOIN ISSUE_ASSIGNED IA "
+ "ON I.issue_number = IA.Issue_number "
+ "LEFT JOIN USERS U "
+ "ON U.id = IA.assigned_to_user_id "
+ "LEFT JOIN USERS US "
+ "ON US.id = IA.assigned_by_user_id ").list();
return allIssueList;
}
query in hibernate returns
PER-1675 Perform - Evaluation Form Export does not pull any data in Legacy Export Tool (Due 8/14) Ameh Ameh
PER-2048 Calculation of scores fails when the lower/upper bound value of a calculation text result is a Ameh Ameh

I was able to solve it by giving alias to both the column somehow hibernate gets confused between the two columns

Related

Query String with native query and ordered parameter, sql doesn't work

I have the following code
#Query(nativeQuery = true, value = "select e.* from event e"
+ " join league l on (l.id = e.league_id)"
+ " join sport s on (l.sport_id = s.id)"
+ " join team t1 on (t1.id = e.team_one_id)"
+ " join team t2 on (t2.id = e.team_two_id)"
+ " join country c on (c.id = l.country_id)"
+ " where l.name LIKE %?1%")
Page<Event> getAllEventsFiltered(final PageRequest of, final String filter);
If execute this SQL into database I receive a lot of results but when is executed from java I receive no one result in the same SQL.
I already tried:
where l.name LIKE %?#{escape([1])} escape ?#{escapeCharacter()}
but just works to begins and I needs for both begin and end.
JDBC parameters can only be included in very specific places in a SQL statement. They are not replaced as strings in the SQL statement but they are applied. The specific valid places change from database to database, and also depend on the JDBC driver variant/version.
The general rule is that a parameter can be applied where a single value would be present. String parameters should not be enclosed in single quotes as a VARCHAR would be.
One option to make it compliant, is to place the parameter isolated from other text, for example by using the CONCAT() function. Your query could be rephrased as:
#Query(nativeQuery = true, value = "select e.* from event e"
+ " join league l on (l.id = e.league_id)"
+ " join sport s on (l.sport_id = s.id)"
+ " join team t1 on (t1.id = e.team_one_id)"
+ " join team t2 on (t2.id = e.team_two_id)"
+ " join country c on (c.id = l.country_id)"
+ " where l.name LIKE concat('%', ?1, '%')") // change here
Nevertheless, the specific syntax change can be different depending on the database you are using (that you haven't mentioned).

Number of characters in sql query result

I am using Spring 3.1.1 with Hibernate 4 and a MSSQL database. Finally, I have been able to query my database with joins in my table that returns the correct answers. Although, it seems that it does not return the entire strings of my messages, but cuts at 29/30 digits. Here is my query:
SQLQuery sql = this.getCurrentSession().createSQLQuery(
"SELECT event.id as eventid, CAST(event_type.type_name AS varchar) as eventtype, event.check_date, event.event_date, event.status, CAST(event_message.message AS varchar) as eventmessage " +
"FROM event_log event " +
"LEFT JOIN event_type " +
"ON (event.event_type_id = event_type.id) " +
"LEFT JOIN event_message " +
"ON (event.event_message_id = event_message.id) " +
"WHERE event.event_type_id = " + jobId +
"ORDER BY eventid");
The result can be:
4506 Database 2014-01-15 14:14:15.02 2014-01-15 14:14:15.02 false Database-connection cannot be
Where the columns are id, task_name, check_date, event_date, status and the message-string at the end. .
The result goes to a ArrayList<Object[]> where I read row[0] etc. to get the entities in the row. The string message gets cut after 29 digits, which is disturbing. Why does it cut the string and how can I fix this? In my database the string exists in it's full and is entitled 400 characters max.
I know this is probably not the best way to query my database, but it will do for my application since it works.
You are using varchar without a length. Never do this!
Replace:
CAST(event_type.type_name AS varchar)
With something like:
CAST(event_type.type_name AS varchar(255))
In some contexts, the default length is 32. In some it is 1. In general, though, always specify the length.
EDIT:
Actually, you probably don't even need the cast. Why not just have event_type.type_name in the select list?

JPA avoiding multiple subquery

I need a little help setting up my query. I don't want to have to make multiple selects to form basically the same sub-query if I can avoid it. In a nut shell, I have Objects called TimeSlot that are used to track several details. Those TimeSlot's are items that are paid on. When its time for the TimeSlot to submit for a reimbursement they are used to create a PayableTimeSlot. Before the TimeSlot can be paid I need to make sure it has not been paid already.
As it sits the following is my query:
#NamedQuery(
name = "TimeSlot.by.person.academy.id.by.contract.date",
query = "select distinct ts
from TimeSlot ts
join ts.invitedInstructors ii
join ts.academyClass ac
join ac.academy a
where ii.person.id = ?
and a.id = ?
and ts.schedule.startDateTime BETWEEN ? AND ?
and ts.id not in (select e.id from PayableTimeslot pts join pts.event e)
and ? not in (select e.claimant from PayableTimeslot pts join pts.event e)")
As you can see I am already selecting an element from the PayableTimeSot for the first not in. Is there a way to expand the sub-query into:
(select e.id, e.claimant from PayableTimeslot pts join pts.event e) I am just not sure how to check for multiple items not in the sub-query. By all means if there is a better attack of the problem than the way I am doing it let me know.
Unless you all think the multiple selects wont be a big deal... There will be on average 30-50 entry's a week into the table with each entry being copied (for an audit trail) upwards of 7-9 times.
Okay so after some thinking this is what I came up with. I was indeed trying to answer the problem in the wrong way... I was doing two sub querys when all I needed was a where on the first thus combining the two.
#NamedQuery(
name = "TimeSlot.by.person.academy.id.by.contract.date",
query = "select distinct ts "
+ "from TimeSlot ts "
+ "join ts.invitedInstructors ii "
+ "join ts.academyClass ac "
+ "join ac.academy a "
+ "where ii.person.id = ? "
+ "and a.id = ? "
+ "and ts.schedule.startDateTime BETWEEN ? AND ? "
+ "and ts.id not in (select e.id from PayableTimeslot pts join pts.event e where pts.claimant = ?)")

sql query to retrieve sum of contact records that match to one user with mysql and java

I have two table user and contact, each user can have multiple contacts
I want to draw a graph (camembert) with JFreeChart(java library) to present the number of contacts that has each user
I tested :
select u.name, sum(c) from user u, contact c
but I have
unknown column c in field list
here are the structures of tables :
utilisateur = idutilisateur, identifiant, motdepasse, nom, prenom
contact = idcontact, ............, idutilisateur
How can I achieve that,
and also, please give me links to tutorials for learning to make queries like that because always I have this problem and I find only basic tutorials
thank you in advance
You need to reference the column of the table that you're trying to count, not just the table itself.
if you try:
select u.name, count(c.ID)
from user u, contact c
You can count all records that have a value in the ID field. If this is a primary key, then all records should have this field. Note the change from sum to count.
This won't fully solve your problem. You also have to let sql know that the two tables are related by joining:
JOIN contact
ON user.ID=contact.userID
Put this after the from user u instead of , contact c
For a good start to learning sql, try here: http://www.w3schools.com/sql/default.asp
String sql1 = "SELECT u.nom, COUNT(c.idcontact) ContactsCount FROM utilisateur u LEFT " + "JOIN contact c ON u.idutilisateur = c.idutilisateur " + "GROUP BY u.nom";
sql = "SELECT u.nom + ' ' + u.prenom dd, COUNT(c.idcontact) FROM utilisateur u " + "LEFT OUTER JOIN contact c ON u.idutilisateur = c.idutilisateur GROUP BY u.nom + ' ' + u.prenom";

Complex SQL query to Hibernate HQL statement

Following SQL query:
select distinct hotel.country 'Country', hotel.id 'Hotel ID', hotel.Name'Name', room.id 'Room ID'
from room, stay, reservation, hotel
where
(stay.roomid = room.id)
and (stay.reservationid = reservation.id)
and (reservation.status != 'Booked' AND reservation.status != 'CheckedIn')
and (reservation.arrivaldate >= '2012-08-08')
and (reservation.leavedate <= '2012-08-15')
and (room.hotelid = hotel.id)
order by hotel.country, hotel.id, hotel.name, room.id asc
This will give me a list of available rooms per hotel per country. Now I have to put this in HQL, but I can't do so because of this:
Query query = session.createQuery("from room, stay, reservation, hotel where stay.roomid = room.id");
This doesn't work becuase stay.roomid is a Room object whereas room.id is just an integer. I'm pretty new to Hibernate/HQL and the reference manual didn't really bring me anywhere... How can I "convert" (scary word, I know this doesn't involve actual converting) this SLQ query to a HQL statement? Thanks.
UPDATE
Using a join result in the same problem
Query query = session.createQuery("" +
"from Stay stay " +
"join stay.ReservationID reservation " +
"join stay.RoomID room " +
"join room.HotelID hotel " +
"where (stay.RoomID = room.ID)");
I'm really missing something (probably very logical) here...
You haven't shown your entities, but, just as you would use joins in SQL, you need to use joins in HQL:
select ...
from Stay stay
join stay.reservation reservation
join stay.room room
join rom.hotel hotel
where (reservation.status != 'Booked' AND reservation.status != 'CheckedIn')
and (reservation.arrivaldate >= '2012-08-08')
and (reservation.leavedate <= '2012-08-15')
The Hibernate documentation has a whole chapter on HQL, and a section of this chapter about associations in HQL.

Categories

Resources