I have table having lot of information. I am not loading all the information while updating this table from view page.
Below is my code to update the table using hibernate
HibernateTemplate hibernateTemplateObj = getHibernateTemplate();
hibernateTemplateObj.update(myEntityBean);
Above one was updating the fields but the fields which are not visible on my view page will be updated with blank.
So, I used below one...
HibernateTemplate hibernateTemplateObj = getHibernateTemplate();
hibernateTemplateObj.update("myRequiredField", myEntityBean);
As per documentation here it says if I use update("string",entity) it will update that fields. But it's not working as same.
Can any one please suggest something.
I found some posts.
post1
post2
It says, I need to create queries. But I don't know how to create queries from it?
If any one have any idea.. Please help. I think it's known issue from those posts.
You can create a query with the Session object like this.
SessionFactory factory= HibernateUtil.getSessionFactory();
session = factory.openSession();
session.beginTransaction();
Query query = session.createQuery("Select c.productList from Cart c Where c.cartId=:cartId");
query.setParameter("cartId", cart.getCartId());
List productList=(List) query.list();
session.getTransaction().commit();
While you know what kind of object should return from query you can cast it and use it.
You can write native query or hibernate query but I think hibernate query is easier.
Related
We use Hibernate and annotations to map our db and entities. But for some data tables I don't want entity classes (Because these table names and all are keep changing) so that the application will be more dynamic
So is it possible using hibernate to load data from a table without a entity class?
If so how?
Hibernate provides a way to execute SQL query and to map it to an entity or any class : native sql queries.
Use plain JDBC. I'm not sure what you mean by "table names and all are keep changing" but it sounds like a bad idea to me.
What you could do is create the sql query using string concatenation then use plain JDBC to execute it. That way you can keep table names dynamic.
If Persistence class won't be used, then the data encapsulation won't occur thus data can be accessed directly.
Hibernate Queries interact with the POJO class to fetch data.
Query, Criteria, HQL all the classes use the POJO for fetching data.
Hibernate Framework was mainly designed for the ORM Mapping.
Thus without POJO class, not possible to interact with the database.
Thus using JDBC connection would be the option left.
Use Dynamic models introduced in Hibernate 5 version - 5.4.0.Final
Hibernate Dynamic Models
To achieve this you will need HBM files created.
Session s = openSession();
Transaction tx = s.beginTransaction();
Session s = openSession();
// Create a customer
Map david = new HashMap();
david.put("name", "David");
// Create an organization
Map foobar = new HashMap();
foobar.put("name", "Foobar Inc.");
// Link both
david.put("organization", foobar);
// Save both
s.save("Customer", david);
s.save("Organization", foobar);
tx.commit();
s.close();
Here Customer & Organization are table names
Organization is Parent of Customer.
Click on the above link for more details
i have written a small piece of code like this. i need all the students and they phones in a one to many relationship.
public ArrayList<Student>getListOfStudents()
{
Session session = getHibernateTemplate().getSessionFactory().openSession();
Criteria like = session.createCriteria(Student.class).setFetchMode("phone",FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
prepareForSelect(like);//some filtering
like.addOrder(Order.asc("name"));
ArrayList<Student> results = new ArrayList<Student>(like.list());
session.close();
return results;
}
this is working very good but i need to tweak it because i need to implement the same criteria filtering in phone as well i have redesign my snippet to something like this.
public ArrayList<Student>getListOfStudents()
{
Session session = getHibernateTemplate().getSessionFactory().openSession();
Criteria like = session.createCriteria(Student.class).setFetchMode("phone",FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
prepareForSelect(like);//some filtering
Criteria innerCriteria = like.createCriteria("phone");
prepareForSelect(innerCriteria);//same filtering but in phone now..
like.addOrder(Order.asc("c01"));
ArrayList<Student> results = new ArrayList<Student>(like.list());
session.close();
return results;
}
but hibernate has changed from left outer join to a inner join and when i run the data in the same methods the before code was running i can see a error is throw.
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.generic.model.Student.phone, no session or session was closed.
my question is what i am doing wrong how can i apply the filters and get the joins correctly thanks a lot.
Well, the problem is that the phones of a student are not eagerly fetched. And since you are closing the session, when you are try to access the phones you are getting LazyInitializationException.
But you are asking yourself I had set the fetch mode to eager by using setFetchMode("phone",FetchMode.JOIN) and it was working just fine. The thing is, there is a bug in Hibernate which disables eager fetching when you add an inner query to a criteria. It is still open. See here:
https://hibernate.atlassian.net/browse/HHH-3524
And if you have time you can take a look at here:
https://forum.hibernate.org/viewtopic.php?f=1&t=944439
If you do, make sure you read the second page, it gets funnier.
So my suggestion is to make the fetch eager at the class level, by using fetch=FetchType.EAGER or switch to CriteriaBuilder (JPA).
I have the following code:
Person a = new Person();
a.setName("John");
Session session = openHibernateSession();
session.beginTransaction();
session.saveOrUpdate(a);
Criteria critera = session.createCriteria(Person.class);
critera.add(Restrictions.eq("name","John"));
Person personFromCache = (Person) criteria.uniqueResult();
...
session.commit();
What I want is to have the ability to search objects from both the database and Hibernate's cache. The following example returns null upon calling uniqueResult. Is there any way to retrieve saved objects that have not yet been committed to the database?
If you are searching other than ID then Hibernate will not use first level cache. Hibernate get and load is related to first level cache by default but criteria query is not. In your case there are two solution from my side
By flushing session = Just flush your session like this session.flush(); while doing so data from session will be synchronize to database hence Id will ge generated and as result Criteria query will find the result in database and will result list to you.
Enable hibernate second level cache = You can enable second level cache by hibernate cache providers like ehCache and apply the trick.
You can use the StatelessSession but be warned:
those entitys are not bound to any session and you will get Exceptions if you like to resolve relations or lazy fields!
session.beginTransaction();
session.saveOrUpdate(a);
session.flush();
Criteria critera = session.createCriteria(Person.class);
critera.add(Restrictions.eq("name","John"));
Person personFromCache = (Person) criteria.uniqueResult();
We do some similar things except using TestNg test framework. Several of the answers discuss the session.flush() method call. This is correct. The call to flush tells Hibernate to do several things, including making sure that all database calls currently waiting in the queue get executed and cleared from the queue.
It returns data even if you are selecting on the basis of username. It is not returning null.
I am using hibernate. i am deleting record using delete method as below.
Session session = sessionFactory.getCurrentSession();
session.delete(pojotobedeleted);
my requirement is after deleting the record, it should return the same deleted record. How can i get the deleted record?
Thanks!
I'd say
Session session = sessionFactory.getCurrentSession();
pojotobedeleted = session.load(Pojo.class, id); /* not necessary if loaded before */
session.delete(pojotobedeleted);
return pojotobedeleted;
Sure there is an extra select statement for doing so, but that is the same with native SQL. The SQL delete does not return the deleted rows, and hibernate can't be better that native SQL.
(If this is not what you wants then I don't understand your question: What is the goal, why not like in my example?)
I created the entity classes of my database with NetBeans. I believe I know how to use EntityManager
(Class) db.createNamedQuery(String name);
but I don't know where to put the statement (database link, login, password) so I learned how to query with
(JDBC4ResultSet) statement.executeQuery(String query);
but it returns the set which I don't know how to transform into Entity class... something like
(Class) statement.execureQuery(String query).toEntity(Class);
would be nice. ;-)
Ok, First you need to get an EntityManager from entity manager factory with your persistance unit name (which will be configured in persistance.xml). And then you create an EntityManager.
EntityManagerFactory emf=Persistence.createEntityManagerFactory("persistance_unit_name");
EntityManager em=emf.createEntityManager();
Query query = em.createNamedQuery("namedQueryName"); //this returns a query
List<ENTITIY> result = query.getResultList();
This is just an heads up, You can google 'jpa example' to find out more working examples.