Update an entity obtained from Select in HQL - java

say I have obtained a list of class objects from a SELECT statement like
List<MyClass> something = em.createQuery("SELECT m FROM MyClass m").getResultList();
and I called a few setters
for (MyClass thing : something)
thing.setName("a name");
What is the syntax to update these class objects back to the database?
Do I write something like UPDATE MyClass m SET m = :newObject . setParameter("newObject", thing);
This is purely about the update syntax, although I know the manager is able to pickup the changes and write those back to the database for me.
Thanks

are you using traditional hibernate or hibernate JPA implementation?
with traditional hibernate, yourSession.saveOrUpdate(thing) should work
if your code is running with JPA hibernate implementation, use em.merge(thing);

Related

Cannot get update query to work with Hibernate

I have a simple update query just to check if update query works:
this.openDBTransaction();
Query updateQuery = session.createQuery(
"UPDATE User AS usr SET usr.failedLogins=666 WHERE usr.id='USER_3000'"
);
int result = updateQuery.executeUpdate();
this.closeDBTransaction();
but somehow DB is not update with desired value. result came as 1 so something took place but for sure not update query.
Any clue what is going on?
You should use #Transactional annotation so that the compiler knows that the transaction is manipulating the database, thus permits to perform Data Manipulation queries or it will simply execute it as a Data Definition Language query.
Look at the code snippet below, for example,
#Transactional
public Employee editEmployee(Employee employee) { //employee is the data you got through post
return entityManager.merge(e1);
}
Also, the best practice is to always implement Data Access Object Interface and its implementation and define your queries in the implementation.
I hope this helps.

Java HibernateCriteria setFetch not Working

i have a Criteria like this
final Criteria criteria = session.createCriteria(Computer.class)
final Criteria studentCriteria = criteria.createCriteria("student","s");
final Criteria schoolCriteria = studentCriteria.createCriteria("school");
everything works OK. but in SchoolCriteria i need the Address which is a property of the School entity
my question is why this is not working
schoolCriteria.setFetchMode("address",FetchMode.JOIN);
i could not see the JOIN in the SQL statement
i just thought that if i am already in the schoolCriteria i could just get the address..
but this is working
criteria.setFetchMode("student",FetchMode.JOIN);criteria.setFetchMode("student.school",FetchMode.JOIN);criteria.setFetchMode("student.school.address",FetchMode.JOIN);
why this.
i am using Hibernate 4.1.5
thanks a lot.
Because you cannot directly fetch child object without fetching parent. when you are trying to do schoolCriteria.setFetchMode("address",FetchMode.JOIN); means you want address object (which is a property of the School entity) after even session get closed but school object is loaded so how can you set address object into student.
You have to do like JamesB given, Read More # Spring Roo doesn't add FetchType.LAZY for fields in .aj files, Should I do it manually?
I think you need to chain the joins together like this:
session.createCriteria(Computer.class)
.setFetchMode("student", FetchMode.JOIN)
.setFetchMode("school", FetchMode.JOIN)
.setFetchMode("address", FetchMode.JOIN)

utilizing JPA Named Queries

When I create an Entity class from a database in NetBeans, it gives me the option to create Named Queries from persistent fields. Accordingly, I see these named queries listed at the top of my Entity class.
What exactly are these queries, and how can I utilize/"call" them?
I'm aware this question is more general than is preferred on SO, so I'm happy to accept a link to a tutorial that answers these questions, but I've been unable to find one myself.
See
JPA Named Queries
If you have:
#NamedQuery(name="Country.findAll", query="SELECT c FROM Country c")
public class Country {
...
}
Use with:
TypedQuery<Country> query = em.createNamedQuery("Country.findAll",Country.class);
List<Country> results = query.getResultList();
See also:
Annotation Type NamedQuery
Tutorial: Build a Web Application (JSF) Using JPA

How to bulk delete from element collection in jpa

I'm using jpa 2.0 and I have the following entity:
#Entity
public class Folder{
#ElementCollection
#CollectionTable(name="folder_files")
private Set<String> files;
// .....
}
Given a file name, I would like to delete all entries where files == theGivenFileName. In sql it would be something like this:
Delete from folder_files where files = XXX
Is there a way to perform this query using criteria-api?
If not, is there a way to perform this query using jpql?
UPDATE:
I think my question was not clear enough:
Since jpql uses entities (and not tables) I cannot just perform the sql written above plus since I'm using #ElementCollection I don't know how to address this variablr or even deal with it. I would like to delete all entries in that collection (in my case, the files set) which holds a given value, from all entities. Is that possible using jpql or (even better) criteria-api?
The Delete FROM clause requires an Entity, so there is no way to delete from an element collection from what I understand.
You can use a native SQL query, or you can map the element collection as a OneToMany to an Entity instead.
You can use the like query just the syntax is slightly changed.
query = em.createQuery("SELECT i FROM Item i WHERE UPPER(i.name) LIKE :keyword ");
query.setParameter("keyword", "%" + keyword.toUpperCase() + "%");
You can read more on following link,
https://forums.oracle.com/forums/thread.jspa?threadID=423742
Updated:
#Noam you can do it: Like in Criteria API
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "Fritz%") )
.add( Restrictions.between("weight", minWeight, maxWeight) )
.list();
Kindly read more on it at following link:
http://ctpconsulting.github.com/query/1.0.0.Alpha3/criteria.html
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
This cannot be done. Via JPQL it does not work because DELETE statement can only be applied to entities. Excerpt from JPA 2.0 specification:
Bulk update and delete operations apply to entities of a single entity
class (together with its subclasses,if any).
...
delete_statement ::= delete_clause [where_clause]
delete_clause ::= DELETE FROM entity_name [[AS] identification_variable]
Also it doesn't work via Criteria API. CriteriaQuery supports only selecting - not updates or removals.
You have to go for native SQL.

How Can I Query a DB for ResultSet which is not Mapped into an Entity(JPA, JBoss)

I'm running an application in JBoss and Using JPA.
For a report I need a group by query which I expect to return a result set with the following structure example:
count,idA,idB
I did not find a way to implement this in JPA.
What are my best options for implementing this considering I'm developing in JBoss 5, EJB3
You can use a custom holder class and use the NEW keyword in your query:
SELECT NEW com.mycompany.myapp.MyClass(count, idA, idB)
FROM ...
WHERE ...
Of course, MyClass needs to have the proper constructor defined.
In the case of Native queries, you can create a dummy entity into which the result set can be mapped to (Native query will not be mapped into an Object unless its a real managed entity).
The entity is a dummy as it will not be persisted and it only used for mapping the result set of the native query into this entity.

Categories