-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: Dynamic select passing my model
PostPosted: Fri Jul 21, 2006 7:48 am 
Newbie

Joined: Fri Jul 21, 2006 7:24 am
Posts: 4
Location: Brazil
Hi,

I want to know if there is way to construct a dynamic query just passing my entity model as parameter? So the Hibernate would construct my query according to the values that exist in the model passed as parameter.

Example:

public class UserModel extends AppModel {

private Long id;
private String name;
private String email;
private String login;
private String admin;

// getter and setters
}

So in my DB I have 3 rows with the given values:
ID NAME EMAIL LOGIN ADMIN
1 Steve NULL steve Y
2 BOB NULL bob N
3 John NULL john Y

And I have an UserModel instance with the values
id= NULL
name= NULL
email= NULL
Login= NULL
ADMIN= Y

So I woul like to call a method like:

List GenericDAO.find(AppModel)
with my instance model UserModel as parameter, and it would return a List of UserModel with the row ID # 1 and 3.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 21, 2006 9:33 am 
Expert
Expert

Joined: Tue Apr 25, 2006 12:04 pm
Posts: 260
I suppose you can use similar code in your implementation to simulate dynamism based on your model.

Code:
public GenericDAO {
   public List find( AppModel model ) {
      
      Session session = getSession();
      try {
         StringBuffer buffer = new StringBuffer();
         buffer.append( "From UserModel model " );

         if ( model instanceof UserModel ) {
            StringBuffer conditions = new StringBuffer();
            UserModel user = ( UserModel ) model;
            if ( user.getId() != null ) {
               conditions.append( " id = "  ).append( user.getId() );
            }
            if ( user.getName() != null ) {
               conditions.append( " name = '"  ).append( user.getName() ).append( '\'' );
            }
            if ( user.getEmail() != null ) {
               conditions.append( " email = '"  ).append( user.getName() ).append( '\'' );
            }
            if ( user.getLogin() != null ) {
               conditions.append( " login = '"  ).append( user.getName() ).append( '\'' );
            }
            if ( user.getAdmin() != null ) {
               conditions.append( " admin = '"  ).append( user.getName() ).append( '\'' );
            }
   
            if ( conditions.length() > 0 ) {
               buffer.append( " where " ).append( conditions.getString() );
            }
      
         }

         Query query = session.createQuery( buffer.toString() );
         List results = query.list();

      } catch ( Exception ex ) {
         ex.printStackTrace();
      }

   }
}


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 21, 2006 9:47 am 
Newbie

Joined: Fri Jul 21, 2006 7:24 am
Posts: 4
Location: Brazil
look down


Last edited by Gabriel Borges Guedes Lim on Fri Jul 21, 2006 9:52 am, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 21, 2006 9:50 am 
Newbie

Joined: Fri Jul 21, 2006 7:24 am
Posts: 4
Location: Brazil
bkmr_77,

I can't do this because this is not dynamic, if I pass another class model, like ProductModel, I wouldnt have the properties email, login, admin , etc.....

Understand?

I get what I want doing the following, but I'm fear that this isn't ok, because I make setString for all properties, even if they are Long or Date or what else.... But it works with Long, and I think it will work with other variable types too.

Anybody have any sugestion?

Code:
   public static List search(AppModel appModel){
      
      Session session = HibernateUtil.getSessionFactory().getCurrentSession();
      
      String model = appModel.getClass().toString();
      model = model.substring(model.lastIndexOf(".")+1);
      
      StringBuilder sb = new StringBuilder()
         .append(" from " ).append(model).append(" model ");
      
      Map mapKeyValue = obterMapKeyValueBean(appModel);
      Set setKeyValue = mapKeyValue.entrySet();

      boolean whereUtilizado = false;
      for (Iterator iter = setKeyValue.iterator(); iter.hasNext();) {
         
         Entry entry = (Entry) iter.next();
         
         if (!desprezarKey(entry.getKey()) && entry.getValue()!=null && !entry.getValue().equals("")){
            
            if (!whereUtilizado){
               sb.append(" where model.").append(entry.getKey()).append(" = :").append(entry.getKey());
               whereUtilizado = true;
            }
            else{
               sb.append(" AND model.").append(entry.getKey()).append(" = :").append(entry.getKey());
            }
         }
      }
      
      Query query = session.createQuery(sb.toString());
      
      for (Iterator iter = setKeyValue.iterator(); iter.hasNext();) {
         
         Entry entry = (Entry) iter.next();
         
         if (!desprezarKey(entry.getKey()) && entry.getValue()!=null && !entry.getValue().equals("")){
            
            query.setString((String)entry.getKey(), (String)entry.getValue());
         }
      }      
         
      return query.list();
   }
   
   private static Map obterMapKeyValueBean(AppModel appModel) {
      
      BeanUtilsBean beanUB = BeanUtilsBean.getInstance();
      
      Map mapProperties = null;
      try {
         mapProperties = beanUB.describe(appModel);
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      
      return mapProperties;
   }


   private static boolean desprezarKey(Object key) {

      String chave = (String) key;
      
      String[] desprezar = {"id", "versao", "class"};
      
      for (int i = 0; i < desprezar.length; i++) {
         
         if (chave.equals(desprezar[i])){
            return true;
         }
      }
      
      return false;
   }


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 21, 2006 12:51 pm 
Expert
Expert

Joined: Thu Sep 22, 2005 10:29 am
Posts: 285
Location: Almassera/Valencia/Spain/EU/Earth/Solar system/Milky Way/Local Group/Virgo Supercluster
I think what you need are queries by example.

From Hibernate org.hibernate.criterion.Example API:
Quote:
Support for query by example.

Code:
List results = session.createCriteria(Parent.class)
     .add( Example.create(parent).ignoreCase() )
     .createCriteria("child")
         .add( Example.create( parent.getChild() ) )
     .list();

Quote:
"Examples" may be mixed and matched with "Expressions" in the same Criteria.
...


read:
Hibernate Reference Documentation
Chapter 15. Criteria Queries
15.6. Example queries

Quote:
The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance.
Code:
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
   .add( Example.create(cat) )
   .list();

Quote:
...


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 21, 2006 1:03 pm 
Newbie

Joined: Fri Jul 21, 2006 7:24 am
Posts: 4
Location: Brazil
Its exactlLy this!!!

Thank you very much...

Gracias!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.