Is it possible to delete multiple rows via JPA in a database table via a specific ID?
e.g.
Delete from PERSON_LANGUAGE where PERSON_ID = 125;
Thanks in advance!
Down below is what im currently trying to use without any luck!
public void deletePersonLanguageById(PersonLanguage personLanguage){
PersonLanguage personLanguage1 = em.find(PersonLanguage.class, personLanguage.getPersonId());
em.remove(personLanguage1);
}
I want it to delete everything in my databasetable where the ID = 1
You can use a native query to execute SQL directly against your database
Query q = em.createNativeQuery("DELETE FROM person_language WHERE person_id = 1");
q.executeUpdate();
or a JPQL query:
Query q = em.creteQuery("DELETE FROM Person p WHERE p.personId = 1");
q.executeUpdate();
You can create a custom repository that extends from the JPA Repository and there you add the deleteByPersonId(String personId).
Some more examples here: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.details
Related
I'm trying to delete all the records from a MySQL table (46 records).
The code I have tried. Any suitable answer?
Session hs = connection.NewHibernateUtil.getSessionFactory().openSession();
Criteria cr = hs.createCriteria(Bookmark.class);
Bookmark b;
List<Bookmark> li = cr.list();
for (Bookmark s : li) {
b = new Bookmark();
b.setId(s.getId());
Transaction tr = hs.beginTransaction();
hs.delete(b);
tr.commit();
hs.flush();
hs.close();
}
Error
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [mypojos.Bookmark#7]
You cant delete objects like that. You would first have to get the object from db and then you can delete using hs.delete(b); this is usually used when you have to cascade changes to associated objects.
Best approach in this case is to use HQL query something like this.
String stringQuery = "DELETE FROM tablename";
Query query = session.createQuery(stringQuery);
query.executeUpdate();
when i run my query in database visualizer its working perfectly, but i think there are some issues in syntax when i convert it in my DAO class method.
I want to get whole data against the name provided
In Visualizer:
SELECT first_name,last_name,nic,phone,email FROM x_hr_user where (first_name = 'Irum');
Now in Dao
public List<XHrUser> findXHrUserByNameInTable()
{
String name ="Irum";
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = (name)");
List<XHrUser> list = query.getResultList();
return list;
}
Instead of showing single row, it displays whole data Table
Thank you
Your current query is not valid JPQL. It appears that you intended to insert the raw name string into your query, which could be done via a native query, but certainly is not desirable. Instead, use a named parameter in your JPQL query and then bind name to it.
String name = "Irum";
Query query = em.createQuery("SELECT x FROM XHrUser WHERE x.firstName = :name")
.setParameter("name", name);
List<XhrUser> list = query.getResultList();
You have to write query as below. where : is used for variable
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = :name");
I'm new to hibernate and I've this SQL query which works perfectly
SELECT count(*) as posti_disponibili from occupazione t inner join
(select id_posto_park, max(date_time) as MaxDate from occupazione
group by id_posto_park) tm on t.id_posto_park = tm.id_posto_park and
t.date_time = tm.Maxdate and t.isOccupied = 0
which gives me all the last items with isOccupied = 0
I was porting it into Hibernate, I've tried to use
result = ( (Integer) session.createSQLQuery(query).iterate().next() ).intValue()
to return posti_disponibili but i got this exception
java.lang.UnsupportedOperationException: SQL queries do not currently support iteration
How can i solve this? I cannot find the equivalent HQL query
Thank you
I would suggest you to use
Query#uniqueResult()
which will give you single result.
select count(*) .....
will always return you a single result.
Hibernate support it's own iterator-like scroll:
String sqlQuery = "select a, b, c from someTable";
ScrollableResults scroll = getSession().createSQLQuery(sqlQuery).scroll(ScrollMode.FORWARD_ONLY);
while (scroll.next()) {
Object[] row = scroll.get();
//process row columns
}
scroll.close();
I want to update a specific field in the database Persons table by using HibernateTemplate. I am trying to do like this but this not working.
public void updateDate(int Id,Date receivedDate) {
Id = 10;
receivedDate = 2012-11-12;
String queryString = "update Persons set recievedDate=? where Id=? ";
getHibernateTemplate().update(queryString, new Object[] { Id, receivedDate });
}
I am getting an exception "UnkownEntity" when I run this query. Can I do update of a specific field at all by using HibernateTemplate? Is there any other alternate to do specific field update?
update method in getHibernateTemplate does not allow hql query to execute. It only allows hibernate entity object.
See link hibernate template update method
In your case Hibernate tries to resolve update Persons set recievedDate=? where Id=? as an entity.
Solution:
Query q = s.createQuery("update Persons set recievedDate=:recievedDate where Id=:Id");
q.setString("recievedDate", "some date");
q.setString("Id", "54");
q.executeUpdate();
Hope its clear.
You have to list your classes in your session factory configuration.
I assume your entity named Person
in HQL you must use java class name, not db table name
if HibernateTemplate is using, here is my solution.
// EntityName is the table to be updated
EntityName entity = hibernateTemplate.find("from EntityName where id=?" , id);
//set the value which has to be updated
entity.setValue(yourNewValue);
hibernateTemplate.SaveOrUpdate(entity);
// above updated the existing Entity table without duplicates
I have a project already developed using java,jsp and JPA (open jpa).Now i want to add a new API to retrieve data from DB.Am not much familiar with JPA.Now i want to take a join of 3 tables Atbl , Btbl, and Ctble ,then check for some conditions and finally populate bean corresopnding to table Atble.I saw a a API as follows
String sql = "SELECT A.* FROM Atble A, Btbl B WHERE A.xyz = B.pqr
AND A.field1 = ? AND B.field2 = 'SubComponent' AND B.field3 = ? ";
Query q = em.createNativeQuery(sql, A.class);
q.setParameter(1,"aa");
q.setParameter(2, "aa");
q.setParameter(3, "cc");
List<A> a = (List<A>) q
.getResultList();
Does it populate bean for A directly?If not how can i populate bean for A
This will return a List, so should work fine.
You may also consider using JPQL instead of a native SQL query, but if you are more comfortable with SQL that is fine.