Not equal query in hql not work - java

I am tring the 'not equal' query in hql.
#Override
public Student findStudentsByYear(String year) {
String queryString = "from Student where year<>:year ";
Query query = sessionFactory.getCurrentSession().createQuery(queryString);
query.setParameter("year", year);
return (Student)query.uniqueResult();
}
but it is not working properly.How to write this query correctly
My student table is
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| studentId | bigint(20) | NO | PRI | NULL | auto_increment |
| course | varchar(255) | YES | | NULL | |
| dob | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| faculty | varchar(255) | YES | | NULL | |
| firstName | varchar(255) | YES | | NULL | |
| gender | int(11) | YES | | NULL | |
| homeAddress | varchar(255) | YES | | NULL | |
| lastName | varchar(255) | YES | | NULL | |
| linkedIn | varchar(255) | YES | | NULL | |
| university | varchar(255) | YES | | NULL | |
| year | varchar(255) | YES | | NULL | |
| user_userId | bigint(20) | YES | MUL | NULL | |
+-------------+--------------+------+-----+---------+----------------+

I know it's late but if anyone is having similar problem, you can use this:
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.ne("year", year));
List<Student> result = criteria.list();
Or this:
List<Student> result = session.createQuery ("from Student where year!=:year").setParameter("year", year).list();
I'm not sure what the problem is in above example as Samantha did not provide any information what so ever but my guess is that the uniqueResult() is causing trouble because this query returns a list and not one result.

Related

MySQL before insert trigger not invoked when object saved by hibernate orm

I have a before insert trigger in MySQL that works when row is inserted directly (through DB client) into database but DOES NOT work through Hibernate ORM.
Some basic info
MySQL 5.6.26 on Debian Jessie 8.6
MySQL Connector Java 5.1.40
Hibernate ORM 5.2.4
the Product table
+----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| prd_no | varchar(6) | YES | UNI | NULL | |
| prd_ty | varchar(20) | NO | | NULL | |
| prd_name | varchar(50) | NO | | NULL | |
| prd_name_short | varchar(10) | NO | | NULL | |
| prd_cat | varchar(20) | NO | | NULL | |
| prd_tax_ty | varchar(20) | NO | | NULL | |
| prd_price_ty | varchar(20) | NO | | NULL | |
| prd_norm_avail | tinyint(3) unsigned | NO | | 1 | |
| ppp_id | int(10) unsigned | YES | MUL | NULL | |
+----------------+---------------------+------+-----+---------+----------------+
My trigger
DELIMITER $$
CREATE TRIGGER tg_product_insPrdNo BEFORE INSERT ON product
FOR EACH ROW
BEGIN
IF NEW.prd_ty = 'ns' THEN
SET NEW.prd_no = fn_getPrdNoNextAI();
END IF;
END $$
DELIMITER ;
Function that gets called by the trigger
DELIMITER //
CREATE FUNCTION fn_getPrdNoNextAI()
RETURNS INTEGER SIGNED
BEGIN
DECLARE last_prd_no INTEGER SIGNED;
SELECT (MAX(CAST(product.prd_no AS SIGNED))) INTO last_prd_no FROM product;
IF last_prd_no IS NULL THEN
SET last_prd_no = 0;
END IF;
RETURN last_prd_no+1;
END //
DELIMITER ;
Java code (abbreviated) for inserting row
Session session = AES_Server.getSessionFactory().openSession();
Transaction tx = null;
int prdID = -1;
try {
tx = session.beginTransaction();
prdID = (int) session.save(prd);
tx.commit();
} catch (HibernateException he) {
if (tx != null)
tx.rollback();
} finally {
session.close();
}
return prdID;
Basically, my DB trigger will only auto-insert value for prd_no field if prd_ty is of value 'ns'. This works fine when inserting directly into the DB but when using hibernate to insert, no value is inserted.
Any pointers would be much appreciated. Cheers.

HQL left outer join with missing mapping

I am using hibernate/hql to create my querys.
Now I got a problem I'm stuck on for quite some hours now, to understand the situation here is
my sorrounding:
I got 3 Tables I need to get Informations from, with the connection/assignment tables I got 5 overall.
The Informations I need are the Key, the Type and the SourceFile, but the special case here is
that the sql will be done while importing new data, so I want to first check if the data is
already existent, or partially existent.
My query needs to always give me the key, no matter what Type or SourceFile
if the Key itself is already in the Database, also I then only want the key and not the other
Informations. (Key matches but SourceFile and Type do not, so I want only the key back)
If the Key is existent with the exact same Type and SourceFile I want to get all Informations.
The Tables are:
(heads up: FK_K_ID is saved as a object with the name key,
FK_S_ID is saved as Source and FK_T_ID is saved as Type)
Key:
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| K_ID | bigint(20) | NO | PRI | NULL | auto_increment |
| key | varchar(255) | NO | | NULL | |
| deleted | boolean | NO | | FALSE | |
+-------------+--------------+------+-----+---------+----------------+
KeyType:
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| KT_ID | bigint(20) | NO | PRI | NULL | auto_increment |
| FK_K_ID | bigint(20) | NO | | NULL | |
| FK_T_ID | bigint(20) | NO | | NULL | |
| deleted | boolean | NO | | FALSE | |
+-------------+--------------+------+-----+---------+----------------+
Type:
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| T_ID | bigint(20) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| description | varchar(255) | NO | | NULL | |
| deleted | boolean | NO | | FALSE | |
+-------------+--------------+------+-----+---------+----------------+
KeySource:
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| KS_ID | bigint(20) | NO | PRI | NULL | auto_increment |
| FK_K_ID | bigint(20) | NO | | NULL | |
| FK_S_ID | bigint(20) | NO | | NULL | |
| deleted | boolean | NO | | FALSE | |
+-------------+--------------+------+-----+---------+----------------+
Source:
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| S_ID | bigint(20) | NO | PRI | NULL | auto_increment |
| sourceFile | varchar(255) | NO | | NULL | |
| deleted | boolean | NO | | FALSE | |
+-------------+--------------+------+-----+---------+----------------+
and here is what I tried so far:
from KeyType kt
right outer join kt.Key k
with k.name in (...)
where k.deleted = false
and ( kt.Type in (...) or kt is null )
The problem with this one is, it kind of does what I want. but I get all keys in the database and the KeyType only where it matches, else null. I don't want to get all keys I just want to get my keys I asked for.
from KeyType kt
right outer join kt.Key k
with k.name in (...)
where k.deleted = false
and (k.name in (...) and kt.Type in (...) or kt is null )
I don't even know what I tried here to be honest. I guess I tried to optimize the first query to only give the keys I asked for.
from KeyType kt
right outer join fetch kt.Key k
where k.deleted = false
and (k.name in (...) and kt.Type in (...) or kt is null )
I also tried to use fetch like this or in other variations but didn't work like I need it to.
from Key k
left outer join KeyType kt on kt.Key.id = k.id
left outer join KeySource ks on ks.Key.id = k.id
inner join Source s on ks.Source.id = s.id
where k.deleted = false
and k.name in (...)
and ( kt.appType in (...) or kt is null )
and ( s.SourceFile in (...) or s is null )
well as expected this doesn't work. I mean its quite simpel to see that it can't work but you try
a lot if you can't get a hang on it.
I tried many more combinations and variations of querys but with no luck. The first query is the closest I got.
I Hope somebody can help me.
PS: I can't change the mapping or the entitys now. I have to work with what I got.
UPDATE:
Alright so I am very close to solving the problem. My query now looks like this:
select k, case when kt.Type not in (...) then null
else 1 end
from KeyType kt
join kt.Key k
where k.name in (...)
Now the only thing I want to to is exchange the 1 with the actual object. But if I do this I get the error "org.hibernate.exception.GenericJDBCException: could not execute query" (running on an oracle db)
Can someone tell me how to solve it?
For my case and sorrounding the way I wanted to do it is not possible.
So I asked coworkers again and we came to the solution we have to do it in single querys.
Just saying this for anyone passing by this post with the same table configuration/problem.

Refer Foreign Key in Hibernate which doesnt have property

I have created a many-to-one mapping in hibernate. The following is the setting
<many-to-one name="groups" class = "Groups" column="cgid" unique="true" not-null="true" cascade="all"/>
In mysql this creates a table with another column called cgid.
mysql> describe CONTACT
-> ;
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| IDCONTACT | bigint(20) | NO | PRI | NULL | |
| FIRSTNAME | varchar(255) | YES | | NULL | |
| LASTNAME | varchar(255) | YES | | NULL | |
| EMAIL | varchar(255) | YES | | NULL | |
| addressId | bigint(20) | NO | UNI | NULL | |
| cgid | bigint(20) | NO | UNI | NULL | |
+-----------+--------------+------+-----+---------+-------+
Now, I need to query based on cgid name.
queryString = "from Contact where cgid = :id";
query = session.createQuery(queryString);
query.setParameter("id", gd.getGid());
contactl = query.list();
Hibernate is constantly complaining about it
could not resolve property: cgid of: domain.Contact [from domain.Contact c where c.cgid = :id]
Not sure, what could be done to resolve this problem. Any suggestions ?
Here queryString = "from Contact where cgid = :id" you are using HQL.cgid is database column name.You must write Contact class variable instead of cgid.And this variable must be mapped with cgid.If you use native sql query with hibernate you can use database column names but with hql can not use.

Hibernate: Unknown column in field list

I am getting the following error from my Hibernate code:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'bulletin0_.bulletin_date' in 'field list'
There is no such bulletin_date column in my table, nor is there such a name in my model class. It's just called date. Here is the line where I'm getting the error.
Query query = session.createQuery("from Bulletin where approved = true");
Here is my model class (I'm leaving out the getters and setters):
public class Bulletin {
#Id
#Column(name="id")
#GeneratedValue
private int id;
#Column(name="date")
private String date;
#Column(name="name")
private String name;
#Column(name="subject")
private String subject;
#Column(name="note")
private String note;
#Column(name="approved")
private boolean approved;
}
Here is my table definition.
+----------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date | varchar(10) | YES | | NULL | |
| name | varchar(30) | YES | | NULL | |
| subject | varchar(50) | YES | | NULL | |
| note | varchar(2500) | YES | | NULL | |
| approved | tinyint(1) | YES | | NULL | |
+----------+---------------+------+-----+---------+----------------+
I had the wrong column names in my Bulletin.hbm.xml file. When I corrected it, the problem was solved.

How to join same table with JPQL

I have a table in my database, which contains sportsresults, and I need to select the last result for a competitor on a specific eventstage from a table.
I have this table:
+----------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------+------+-----+---------+-------+
| EventStageID | int(11) | NO | PRI | NULL | |
| CompetitorID | int(11) | NO | PRI | NULL | |
| Lap | int(11) | NO | PRI | NULL | |
| Time | varchar(255) | YES | | NULL | |
| Status | varchar(255) | YES | | NULL | |
| PitstopCount | int(11) | YES | | NULL | |
| Grid | int(11) | YES | | NULL | |
| FastestLapTime | varchar(255) | YES | | NULL | |
| Substatus | varchar(255) | YES | | NULL | |
| Points | decimal(10,2) | YES | | NULL | |
| Position | int(11) | YES | | NULL | |
| StageType | int(11) | YES | | NULL | |
+----------------+---------------+------+-----+---------+-------+
I can select from the table with normal SQL query like this:
SELECT * FROM
(SELECT EventStageID as esi, CompetitorID as cid, Max(Lap) as MaxLap FROM srt_outright_season_event_stage_result_live WHERE EventStageID = 191666 GROUP BY CompetitorID) as y
LEFT JOIN
(SELECT * FROM srt_outright_season_event_stage_result_live) as x
ON x.CompetitorID = y.cid AND x.Lap = y.MaxLap AND x.EventStageID = y.esi;
Which gives the following result:
+--------+--------+--------+--------------+--------------+------+----------+--------+--------------+------+----------------+-----------+--------+----------+-----------+
| esi | cid | MaxLap | EventStageID | CompetitorID | Lap | Time | Status | PitstopCount | Grid | FastestLapTime | Substatus | Points | Position | StageType |
+--------+--------+--------+--------------+--------------+------+----------+--------+--------------+------+----------------+-----------+--------+----------+-----------+
| 191666 | 4521 | 0 | 191666 | 4521 | 0 | Finished | NULL | NULL | NULL | 2:00.175 | NULL | NULL | 4 | 5 |
| 191666 | 4524 | 0 | 191666 | 4524 | 0 | Finished | NULL | NULL | NULL | 2:04.053 | NULL | NULL | 10 | 5 |
| 191666 | 4533 | 0 | 191666 | 4533 | 0 | Finished | NULL | NULL | NULL | NULL | NULL | NULL | 13 | 5 |
| 191666 | 4538 | 0 | 191666 | 4538 | 0 | Finished | NULL | NULL | NULL | 2:01.218 | NULL | NULL | 6 | 5 |
| 191666 | 5769 | 0 | 191666 | 5769 | 0 | Finished | NULL | NULL | NULL | 2:00.050 | NULL | NULL | 3 | 5 |
| 191666 | 7135 | 0 | 191666 | 7135 | 0 | Finished | NULL | NULL | NULL | 1:59.431 | NULL | NULL | 1 | 5 |
| 191666 | 7138 | 0 | 191666 | 7138 | 0 | Finished | NULL | NULL | NULL | NULL | NULL | NULL | 18 | 5 |
| 191666 | 7610 | 0 | 191666 | 7610 | 0 | Finished | NULL | NULL | NULL | 1:59.486 | NULL | NULL | 2 | 5 |
+--------+--------+--------+--------------+--------------+------+----------+--------+--------------+------+----------------+-----------+--------+----------+-----------+
I have this Entity class:
#Entity(name = "event_stage_result_live")
public class EventStageResultLive {
#EmbeddedId
private PKEventStageResultLive pkEventStageResultLive;
// Composite PK contains EventStageID, CompetitorID and Lap
#Column(name = "Time")
private String time;
#Column(name = "Status")
private String status;
#Column(name = "PitstopCount")
private Integer pitstopCount;
#Column(name = "Grid")
private Integer grid;
#Column(name = "Position")
private Integer position;
#Column(name = "FastestLapTime")
private String fastestLapTime;
#Column(name = "Substatus")
private String substatus;
#Column(name = "Points")
private Float points;
#Column(name = "StageType")
private StageType stageType;
// getters and setters...
}
I think in SQL you can do something like this. I dont think join is required.
select * from srt_outright_season_event_stage_result_live c
where c.CompetitorID = :competitorID and c.EventStageID = 191666
and c.Lap = (select max(d.lap) from srt_outright_season_event_stage_result_live d
where d.CompetitorID = :competitorID and d.EventStageID = 191666 )
Passed to JPQL is
select e from EventStageResultLive e
where e.pkEventStageResultLive.CompetitorID = :competitorID and c.pkEventStageResultLive.EventStageID = 191666
and e.pkEventStageResultLive.Lap = (select max(d.pkEventStageResultLive.lap) from EventStageResultLive d
where d.pkEventStageResultLive.CompetitorID = :competitorID and d.pkEventStageResultLive.EventStageID = 191666 )
Assuming
public class PKEventStageResultLive{
private int CompetitorID ;
private int EventStageID ;
private int Lap;
}
If the name of the properties are different correct the name in the JPQL
And competitorID as a named parameter.

Categories