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
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();
I've a database with many thousands of tables that have been (and continue to be) created with a naming strategy - one table per calendar day:
data_2010_01_01
data_2010_01_02
...
data_2020_01_01
All tables contain sensor data from the same system in the same shape. So a single entity (lets call it SensorRecord) will absolutely map to all tables.
I'd imagined something like this would work:
#Query(nativeQuery = true, value = "SELECT * FROM \"?1\"")
Collection<SensorRecord> findSensorDataForDate(String tableName);
But it does not, and reading around the topic seems to suggest I am on the wrong path. Most posts on dynamic naming seem to state explicitly that you need one entity per table, but generating thousands of duplicate entities also seems wrong.
How can I use JPA (JPQL?) to work with this data where the table name follows a naming convention and can be changed as part of the query?
Parameters are only allowed in the where clause.
You can create custom repository method returns collection of SensorRecord dto. No need to map so many entities. You should get List<Object []> as query result and manually create dto objects.
#Autowired
EntityManager entityManager;
public List<SensorRecord> findSensorDataForDate(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd");
String tableName = "data_" + date.format(formatter);
Query query = entityManager.createNativeQuery(
"select t.first_column, t.second_column from " + tableName + " t");
List<Object[]> queryResults = query.getResultList();
List<SensorRecord> sensorRecords = new ArrayList<>();
for (Object[] row : queryResults) {
SensorRecord record = new SensorRecord();
record.setFirstParameter((Integer) row[0]);
record.setSecondParameter((String) row[1]);
sensorRecords.add(record);
}
return sensorRecords;
}
Could it be just syntax error?
This has worked for me:
#Query(value = "select * from job where job.locked = 1 and job.user = ?1", nativeQuery = true)
public List<JobDAO> getJobsForUser(#Param("user") String user);
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
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");
SQL statement:
UPDATE table SET column = 'new_value' WHERE column = 'old_value'
(same column name)
How to do this in Hibernate?
You may use EntityManager.merge() which can lead to NonUniqueObjectException if there are multiple results are found with same column name.
Better to use NamedQuery ot NativeNamedQuery to achieve this.
My understanding is that you would want to perform batch updates.
I suggest you refer to this link
You can make use of the below code in order to get this done.
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
Do note the below point mentioned in the link.
Joins, either implicit or explicit, are prohibited in a bulk HQL query. You can use sub-queries in the WHERE clause, and the sub-queries themselves can contain joins.