How to add multiple class in criteria to check a column - java

Here is the above code, I just want to add country class to the criteria such that if the deleteflag in country class is false, it should not fetch the states in staveprovince class:
public List<StateProvince> getAllState(Country country)throws HibernateException,ConstraintViolationException {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(StateProvince.class);
criteria.setCacheable(true);
criteria.add(Restrictions.eq("country", country));
criteria.add(Restrictions.eq("deleteFlag", false));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}

I guess country is an attribute of StateProvince of type Country, so in that case your criteria must be the following:
criteria.createCriteria("country").add(Restrictions.eq("deleteFlag", false));

public class StateProvinceDAOImpl implements StateProvinceDAO {
#SuppressWarnings("unchecked")
#Override
public List<StateProvince> getAllState(Country country)throws HibernateException,ConstraintViolationException {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(StateProvince.class,"state");
criteria.setCacheable(true);
criteria.createAlias("state.country", "country");
criteria.add(Restrictions.eqProperty("state.deleteFlag", "country.deleteFlag"));
criteria.add(Restrictions.eq("country", country));
criteria.add(Restrictions.eq("deleteFlag", false));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}

I am assuming you have Country associated in StateProvince. Please comment if this does not solve your problem.
public List<StateProvince> getAllState(Country country)throws HibernateException,ConstraintViolationException {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(StateProvince.class);
criteria.createAlias("country", "country");
criteria.setCacheable(true);
criteria.add(Restrictions.eq(deleteFlag", false));
criteria.add(Restrictions.eq("country", country));
criteria.add(Restrictions.eq("country.deleteFlag", false));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}

Related

How can I avoid duplicate code with the same method body but different return types in Java?

The Idea:
When I was using hibernate I saw that everytime I had to write some sort of code. So I moved them to another method as wrapper. Where there will be functional interface as argument so that I can append some code in those context methods.
Problem:
Here is my two methods. One returns Object while another one is returning List. How can I exactly generify and make those two methods as one so that I can avoid code duplication.
public Object objectReturnContext(Function<Session, Object> function) {
Object object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
object = function.apply(session);
transaction.commit();
} catch (NoResultException exception) {
if (transaction != null) transaction.rollback();
return object;
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return object;
}
public List<T> listReturnContext(Function<Session, List<T>> function) {
List<T> object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
object = function.apply(session);
transaction.commit();
} catch (NoResultException exception) {
if (transaction != null) transaction.rollback();
return object;
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return object;
}
For better understanding, This is my whole class. If anyone can advice me any better way I will be very thankful. I have been into this for last few days.
package com.go_task.database;
import javax.persistence.Table;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
public abstract class QueryExecutionContext <T> {
public Class<T> entity;
public String tableName;
public QueryExecutionContext(Class<T> entity) {
this.entity = entity;
this.tableName = entity.getAnnotation(Table.class).name();
}
public List<T> criteriaContext(CriteriaContextRunner<Session, Root<T>,
CriteriaQuery<T>, CriteriaBuilder, List<T>> runner) {
List<T> data = new ArrayList<>();
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery =
criteriaBuilder.createQuery(entity);
Root<T> root = criteriaQuery.from(entity);
data = runner.apply(session, root, criteriaQuery, criteriaBuilder);
transaction.commit();
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return data;
}
public Object singleCriteriaContext(CriteriaContextRunner<Session, Root<T>,
CriteriaQuery<T>, CriteriaBuilder, Object> runner) {
Object data = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery =
criteriaBuilder.createQuery(entity);
Root<T> root = criteriaQuery.from(entity);
data = runner.apply(session, root, criteriaQuery, criteriaBuilder);
transaction.commit();
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return data;
}
public Object objectReturnContext(Function<Session, Object> function) {
Object object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
object = function.apply(session);
transaction.commit();
} catch (NoResultException exception) {
if (transaction != null) transaction.rollback();
return object;
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return object;
}
public List<T> listReturnContext(Function<Session, List<T>> function) {
List<T> object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
object = function.apply(session);
transaction.commit();
} catch (NoResultException exception) {
if (transaction != null) transaction.rollback();
return object;
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return object;
}
public void noReturnContext(Consumer<Session> consumer) {
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
consumer.accept(session);
transaction.commit();
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
}
}
I have extented QueryExecutionContext in my BaseDaoImpl.java later on. So I need to know 2 things.
Is my approch is ok or not. Im using pure hibernate and nothing else. No spring boot here.
If so then tell me how can I solve the code duplication in objectReturnContext() and listReturnContext() method.
The Object/List<T> parameter could be a generic parameter U:
public <U> U returnContext(Function<Session, U> function) {
U object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
object = function.apply(session);
transaction.commit();
} catch (NoResultException exception) {
if (transaction != null) transaction.rollback();
return object;
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return object;
}
U will be inferred depending on what function you pass into the method. If you call it like:
Object o = returnContext(s -> {
...
return new Object(); // just an example
});
Then U is Object.
If you call it like:
List<T> list = returnContext(s -> {
...
return new ArrayList<T>(); // just an example
});
Then U is ArrayList<T>.

Pass Values to a generic Method dynamically

I am using Hibernate and I have Many methods of this type:
public static void modifySchemeEvents(String schmCode, String username) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(SchmEventsTable.class);
cr.add(Restrictions.eq("schmCode", schmCode));
SchmEventsTable evt = (SchmEventsTable) cr.uniqueResult();
evt.setLchgUserId(username);
tx.commit();
} catch (HibernateException asd) {
log.debug(asd.getMessage());
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
}
This updated the database with the username where schmCode is <schmCode> I am attempting to convert to generic so that I do not have to write a separate method for all updates so I have come up with this generic method:
public static <T> T getUpdateObject(Class c, Map<String, ?> params) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
T value = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(c);
for (Map.Entry<String, ?> entry : params.entrySet()) {
cr.add(Restrictions.eq(entry.getKey(), entry.getValue()));
}
value = (T) cr.uniqueResult();
////How to set the values here?***
tx.commit();
} catch (HibernateException asd) {
log.debug(asd.getMessage());
if (tx != null) {
tx.commit();
}
} finally {
session.close();
}
return value;
}
I am attempting to use it this way:
Map<String, String> schemeEventMap = new HashMap();
schemeEventMap.put("schmCode", "CA201");
SchmEventsTable evt = DataOperation.getUpdateObject(SchmEventsTable.class, schemeEventMap);
evt.setLchgUserId(username);
This does not update the table like the first method. I am wondering how to pass the parameters in the generic Method Dynamically.

How do I print an entire table from my database using Java and Hibernate?

How can I print out an entire table from my database and its contents using Java and Hibernate?
My code thus far only prints one line of information that I need. It only prints the author:
package models;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import dao.HibernateDataDAO;
import hibernate.Books;
public class TestModel {
HibernateDataDAO data;
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void test() {
System.out.println("Testing hibernate");
//This Books is just a test, in the real implementation it will be added by the user.
Books books = new Books();
books.setTitle("A Game of Thrones");
books.setAuthor("George RR Martin");
data.insertBooks(books);
Session session = sessionFactory.openSession();
session.beginTransaction();
books = (Books) session.get(hibernate.Books.class, 1);
System.out.println(books.getAuthor());
//int id = 3;
//We set this as 'increment' so that keys are set by database and not by users.
//data.deleteBooks(books, id);
}
public HibernateDataDAO getData() {
return data;
}
public void setData(HibernateDataDAO data) {
this.data = data;
}
}
My table is called books. and there are 3 columns in it: booksKey, title, and author. booksKey is an integer, title/author are strings. How can I print the entire table so that it prints out all the rows of information?
I tried modifying the above code and doing this, however, nothing printed:
Query query = session.createSQLQuery("select *from books");
List<Books> list = query.list();
for(Books test: list) {
System.out.println(test.getAuthor());
}
If someone can please help-preferably show me what code to add/fix, that would be awesome. I can't figure this out at all!
HibernateDataDAO:
package dao;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import hibernate.Books;
import hibernate.Music;
import hibernate.Contacts;
import hibernate.Movies;
//DAO = data access object.
public class HibernateDataDAO {
private SessionFactory sessionFactory;
private Transaction transaction;
public void insertBooks(Books books) {
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.save(books);
transaction.commit();
}
catch (Exception e) {
if (transaction != null) transaction.rollback();
throw e;
}
finally {
session.close();
}
}
public void deleteBooks(Books books, int booksKey){
Session session = sessionFactory.openSession();
try{
transaction = session.beginTransaction();
Object persistentInstance = session.load(hibernate.Books.class, booksKey);
if (persistentInstance != null) {
session.delete(persistentInstance);
}
transaction.commit();
}catch(HibernateException e){
if(transaction!= null) transaction.rollback();
e.printStackTrace();
}
finally{
session.close();
}
}
public void insertMusic(Music music) {
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.save(music);
transaction.commit();
}
catch (Exception e) {
if (transaction != null) transaction.rollback();
throw e;
}
finally {
session.close();
}
}
public void deleteMusic(Music music, int musicKey){
Session session = sessionFactory.openSession();
try{
transaction = session.beginTransaction();
Object persistentInstance = session.load(hibernate.Music.class, musicKey);
if (persistentInstance != null) {
session.delete(persistentInstance);
}
transaction.commit();
}catch(HibernateException e){
if(transaction!= null) transaction.rollback();
e.printStackTrace();
}
finally{
session.close();
}
}
public void insertMovies(Movies movies) {
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.save(movies);
transaction.commit();
}
catch (Exception e) {
if (transaction != null) transaction.rollback();
throw e;
}
finally {
session.close();
}
}
public void deleteMovies(Movies movies, int movieKey){
Session session = sessionFactory.openSession();
try{
transaction = session.beginTransaction();
Object persistentInstance = session.load(hibernate.Movies.class, movieKey);
if (persistentInstance != null) {
session.delete(persistentInstance);
}
transaction.commit();
}catch(HibernateException e){
if(transaction!= null) transaction.rollback();
e.printStackTrace();
}
finally{
session.close();
}
}
public void insertContacts(Contacts contacts) {
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.save(contacts);
transaction.commit();
}
catch (Exception e) {
if (transaction != null) transaction.rollback();
throw e;
}
finally {
session.close();
}
}
public void deleteContacts(Contacts contacts, int contactKey){
Session session = sessionFactory.openSession();
try{
transaction = session.beginTransaction();
Object persistentInstance = session.load(hibernate.Contacts.class, contactKey);
if (persistentInstance != null) {
session.delete(persistentInstance);
}
transaction.commit();
}catch(HibernateException e){
if(transaction!= null) transaction.rollback();
e.printStackTrace();
}
finally{
session.close();
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Try this:
Criteria criteria = session.createCriteria(Books.class);
List<Books> list = criteria.list();
for(Books test: list) {
System.out.println(test.getBooksKey + " " + test.getAuthor() + " " + test.getTitle());
}
If you there's any error, then please let me know about it.
You should change your code like following;
Query qry=session.createQuery("from books");
List<Books> user=(List<Books>) qry.list();
session.getTransaction().commit();
session.close();
List<Books> list = query.list();
for(Books test: list) {
System.out.println(test.getAuthor());
}

multiple update with jpa

I need to upgrade a field of several records in bd. How to do this with JPA?. I tried the following but not working:
#Override
public String estadoPedido(List<DetallePedido> lista) {
int cod;
String mensage = null;
for (DetallePedido ped : lista) {
cod = ped.getIdDetalle();
EntityManager em = emf.createEntityManager();
DetallePedido detPed = new DetallePedido();
try {
em.getTransaction().begin();
detPed = em.find(DetallePedido.class, cod);
detPed.setPedEstado("EN PLAN");
em.merge(detPed);
em.getTransaction().commit();
mensage = "detalle seleccionado";
} catch (Exception e) {
mensage = "Error:/p" + e.getMessage();
} finally{
em.close();
}
}
return mensage;
}
Try the following:
#Override
public String estadoPedido(List<DetallePedido> lista) {
EntityManager em = emf.createEntityManager();
//em.getTransaction().begin(); //Consider using Container managed transactions ,
// if you do remove this line and the line above, and have
//entity manager injected !
String mensage = null;
try {
for (DetallePedido ped : lista) {
detPed.setPedEstado("EN PLAN");
em.merge(detPed);
}
mensage = "detalle seleccionado";
em.getTransaction().commit; //consider removing this line and use Container managed transactions!
} catch (Exception e) {
mensage = "Error:/p" + e.getMessage();
} finally{
em.close();
}
return mensage;
}

Update data with Struts and Hibernate

i have to update some rows in database using Hibernate and Struts2:
the method DAO where i put the requete is:
public void modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{Query query = session.createQuery("Update Processus set selectionne = '1' where"+cond );
// query.setString("idproc",idprocessus);
// query.setLong("idsi", identifiantsi);
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
In my action class where i call the DAO, i specify the cond:
public String update(){
cond="id_processus="+checked;
procdao.modifier(cond);
return SUCCESS;
}
can u help me it doens't show any error in the console but the row's value don't change!!!!
Following code could be helpful: Processus Table name selectionne and idproc are column name
You need to execute the query
To check the number of updated rows.
public Boolean modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Boolean returnValue = false;
try {
Query query = session.createQuery("Update Processus set selectionne = '1' where idproc=:cond");
query.setString("cond", cond);
int noOfUpdate = query.executeUpdate();
returnValue = (noOfUpdate > 0);
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return returnValue;
}

Categories