im familiar with this following way to delete the data (just the data ,not the entity itself)
from the entity
entityManager.getTransaction().begin();
entityManager.createQuery("DELETE FROM " + className)
.executeUpdate();
entityManager.getTransaction().commit();
there is another way to do that like to provide the entityname and then reomve all the data .
You're not using SQL in your code but JPQL, JPA Query Language.
There is no other way to delete all data at once, except by loading all of them and deleting them one by one. It's not even possible with criteria queries since they don't support delete operation yet.
Well.. in this case both NativeSQLQuery and JPQL resolve to the same thing. What you did is JPQL way. The following you could write a nativeSQLQuery
EntityManager em = ...;
Query query = em.createNativeQuery ("SELECT * FROM EMP", Employee.class);
Related
Can anyone please tell me the difference between Hibernate's:
createCriteria
createQuery
createSQLQuery
Can anyone tell me what data these three functions return, c.q. direct me to a proper and simple link to study these Hibernate functions?
To create query in the Hibernate ORM framework, there is three different types. The following are the three ways to create query instance:
session.createQuery()
session.createSQLQuery()
session.createCriteria()
Look into the details of each category in detail.
Session.createQuery()
The method createQuery() creates Query object using the HQL syntax. For example:
Query query = session.createQuery("from Student s where s.name like 'k%'");
Session.createSQLQuery()
The method createSQLQuery() creates Query object using the native SQL syntax. For example:
Query query = session.createSQLQuery("Select * from Student");
Session.createCriteria()
The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API.
Criteria criteria = session.createCriteria(Student.class);
1. session.createQuery()-> Can create query using HQL and can perform CRUD Operations
Example:
Query query = session.createQuery("from Student");
List list=quey.list();
Query query = session.createQuery("update Student where studentid=9");
int result=query.executeUpdate();
Query query = session.createQuery("delete Student where studentid="+ studentId);
int result=query.executeUpdate();
Query query = session.createQuery("insert into Student where studentid="+ studentId);
int result=query.executeUpdate();
session.createSQLQuery()-> Can create query using SQL and can perform CRUD Operations
session.createCriteria()->Can create query using Criteria API and can perform only Read Operations
------------------------
PERSON
------------------------
**DB_Column**| **POJO**
PERSON_ID | personID
------------------------
createQuery()
you are using pojo fields. Using HQL syntax.
Query query = session.createQuery("from Person s where s.personID like 'A%'");
// returns:
List<Person> persons = query.list();
createSQLQuery()
You are using Native|DB fields.
After googling some site, Came to know this will also clear the cache as hibernate don't know the what you have executed.
Query query = session.createSQLQuery("select s.* from Person s where s.person_ID like 'A%'");
// returns:
List<Object[]> persons = query.list();.
createCriteria()
Create sql query using Criteria object for setting the query
parameters.
Useful when switching DB.
Read only query
Criteria criteria = session.createCriteria(Person.class);
criteria.add(Restrictions.like("personId", "A%"));
List<Person> persons = criteria .list();
createSQLQuery -- is for native sql querying which is selected by you with jdbc driver cfg or something else.
createQuery -- is for hibernate querying which provides you independent querying which makes you run that on many databases using API and more other advantages.
createCriteria -- is better to use for simple querying on db because of it's simplicity.
I hope this helps you!
Currently i am using the CreateSQLQuery query model to read the data from database using HIbernate. Now, I want to modify my query by using either HQL or Hibernate Criteria. My query looks like as follows.
select concat(d.AREA,' ',d.CITY) as location, a.TRANSFERRED_DATE as ActualTransferDate, concat(c.SCAN_CODE,',',c.SERIAL_NO) as ScanserialCode, c.MODEL_NO as ModelNum, c.ASSET_NAME as AssetName from table_transfer a, table_category b, table_asset c, table_location d where a.ASSET_ID = c.ASSET_ID and b.ASSET_CATEGORY_ID = c.ASSET_CATEGORY_ID and a.TRANSFER_TO_LOCATION=d.LOCATION_ID"
I am not sure how can i can convert this to Hibernate SQL or Criterion based query. Can any one help me?
You can introduce the fields for location and scanserialCode in your entity and mark them as #Formula
e.g.
#Formula("concat(d.AREA,' ',d.CITY)")
private String location;
See an example here or here
Then use join and where in HQL or Hibernate Criteria
I use JPA to add data to Derby DB with eclipse link and when there is duplicated ID.
I got error, there is a way in run-time (with code) to simple delete all the table entries.
I don't need the old entry just new entries in every time that I invoke the program.
I tried with
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();
Query query = entityManager.createQuery("SELECT p FROM Job p ");
List resultList = query.getResultList();
for (Object result : resultList) {
entityManager.remove(result);
}
entityManager.getTransaction().commit();
entityManager.close();
but here I use query before and I don't want to do that I want to delete all the entries and I don't care what is there before.
You can use the SQL DELETE query at runtime everytime the application starts. If you don't post some code, we can't help.
EDIT :
You can execute the query as follows in some earlier transaction or the same transaction before the query:
int deletedCount = entityManager.createQuery("DELETE FROM Job").executeUpdate();
You could either execute a delete query, or configure your persistence unit to recreate the tables when the persistence unit is deployed.
See,
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/p_ddl_generation.htm#BABHEJJI
Does anyone know of a way, if any, to put an external property into a jpa named query?
So for example:
#NamedQuery(name = "Test", query = "select t from ${table.name} t")
As opposed to:
#NamedQuery(name = "Test", query = "select t from TableName t")
Thanks
Annotations are final hence they cannot be changed at runtime, so you cannot do that.
You could define the native query at runtime instead of as a named query and translate the SQL string yourself.
Other solution would be to use some sort of pre compiler on your code, or use some sort of persistence unit event to post process your queries. If you are using EclipseLink, you could use a SessionCustomizer for this, or a SessionEventListener to pre process SQL queries before they are executed.
I'm trying to use JPA with HibernateSearch. I used Example 5.3 in http://docs.jboss.org/hibernate/stable/search/reference/en/html/search-query.html. The results come out as expected.
However, the data coming back is a huge graph. I only need the primary key of the data. So, I tried Example 5.9, but it only shows the Hibernate API. There was not a javax.persistence.Query.setProjection() method.
What can I use to get just the primary key of a search result? Should I try to get the hibernate session from the EntityManager in JPA?
Thanks for any help.
Example 5.3 was a bit misleading. javax.persistence.Query doesn't have to be used. Instead, org.hibernate.search.jpa.FullTextQuery has the setProjection() method that I needed. Here is the resulting code (with fully qualified class names):
//Open JPA session
javax.persistence.EntityManagerFactory emf=javax.persistence.Persistence.createEntityManagerFactory("manager1");
javax.persistence.EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
//Make a FullText EM from the JPA session.
org.hibernate.search.jpa.FullTextEntityManager fullTextSession=org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
//Build the lucene query.
org.apache.lucene.queryParser.QueryParser parser=new org.apache.lucene.queryParser.QueryParser("data1",new org.apache.lucene.analysis.standard.StandardAnalyzer());
org.apache.lucene.search.Query query=parser.parse("FindMe");
//Convert to a hibernate query.
org.hibernate.search.jpa.FullTextQuery query2=fullTextSession.createFullTextQuery(query, SampleBean.class);
//Set the projections
query2.setProjection("id");
//Run the query.
for (Object[] row:(List)query2.getResultList()){
//Show the list of id's
System.out.println(row[0]);
}
//Close
em.getTransaction().commit();
em.close();
emf.close();
query2 does the projection and all is well!