简体   繁体   中英

hibernate HQL delete query nullifies single column

I am working on spring hibernate application and trying to delete from a table using non-id many-to-one relationship based column. Entity classes are:

@Entity  
public class Day {  
@id(name = "DAY_ID")  
dayId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "DAY_ID")
List<Holiday> holidayList;  
...  
}

@Entity  
public class Holiday {  
@id(name="HOLIDAY_ID")
holidayId;  
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "DAY_ID")
Day day;
...
}

I am trying to delete a row from holiday table using hql.

String query = "DELETE FROM Holiday WHERE day.dayId = " + dayObject.getdayId();
Query holidayDeleteQuery = getSession().createQuery(query);
holidayDeleteQuery.executeUpdate();

In the console i am getting proper delete query but on checking DB found out that the row is still there but now the DAY_ID column in holiday table is null. I am not able to figure out why is this happening?
EDIT: help!!! My main problem is why DAY_ID column is changing to null value??

I'm not sure that this is your problem, but in your query you say "DELETE FROM Holidays ...", but your Class name is Holiday . In HQL you should be using Class names rather than table names or anything else. Is this typo in your code or just on here?

Actually after looking further there are a few more problems. This is how I'd write it:

String query = "DELETE FROM Holiday h WHERE h.day = :day";
Query holidayDeleteQuery = getSession().createQuery(query);
query.setParameter("day", dayObject);
holidayDeleteQuery.executeUpdate();

To break it down - use the Class name "Holiday", assign it an alias "h" then reference the day field of the Holiday object ("h.day") and compare it to the actual Day object you have.

What is your ONDELETE foreign key constrain? Might it that other part of your application inserting a row?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM