2013-06-14 6 views
21

Il _ (trattino basso) indicato nella query SQL non è rispettato.Come uscire dal trattino basso nella query stringa in sospensione e SQL?

Esempio:

SELECT * FROM employee WHERE NAME LIKE '%k_p%'; 

Questo corrisponde e porta molte righe a parte le righe che contengono k_p

Qualcuno potrebbe aiutare su come raggiungere questo obiettivo in SQL e anche in Hibernate? Grazie.

+0

È possibile specificare un [carattere di ESCAPE] (http://dev.mysql.com/doc/refman/5.5/en/string-comparison-functions.html#operator_like). Ad esempio LIKE '% k | _p%' ESCAPE '|' . – wisefish

risposta

48

Hai provato scampo:

SELECT * FROM employee WHERE NAME LIKE '%k\_p%'; 

\_ invece di _.

+0

+1 Semplice e diretto –

0

In MySQL Soluzione: select * from users where id like '%k_p%';

In Hibernate 

ecco la soluzione:

List<UserDTO> userDTOList = signUpBusiness.getUserDTODetails("k", "p"); 

chiamare questo metodo

public List<UserDTO> getUserDTODetails(String firstMatch, String secondMatch) { 
    List<UserDTO> userDTOList = new ArrayList<UserDTO>(); 
    Session session = null; 
    try { 
     session = SessionFactoryFpf.getCurrentSession(); 
     Criteria criteria = session.createCriteria(User.class); 
     //MatchMode matchMode = MatchMode.ANYWHERE; 
     //criteria.add(Restrictions.like("id", firstMatch, matchMode)); 
     criteria.add(Restrictions.like("id", "%"+firstMatch+"_"+secondMatch+"%")); 
     List<User> userList = criteria.list(); 
     if (userList.size() > 0) { 
      for (User user : userList) { 
       UserDTO userDTO = new UserDTO(); 
       userDTO.setId(user.getId()); 
       userDTO.setDob(user.getDob()); 
       userDTO.setFullName(user.getFullName()); 
       userDTO.setGender(user.getGender()); 
       userDTO.setEmail(user.getEmail()); 
       userDTOList.add(userDTO); 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     LOG.error("Type of exception occured in getUserDTODetails() is --> "+e); 
    } finally { 
     SessionFactoryFpf.closeSession(session); 
    } 
    return userDTOList; 
} 

Un altro modo commutare il commento nel metodo di cui sopra:

MatchMode matchMode = MatchMode.ANYWHERE; 
criteria.add(Restrictions.like("id", firstMatch, matchMode)); 
//criteria.add(Restrictions.like("id", "%"+firstMatch+"_"+secondMatch+"%")); 
+0

La tua soluzione MySQL sembra sbagliata: hai sostituito un trattino basso con un segno meno (errore?). E se usi un trattino di sottolineatura anziché un segno negativo, otterrai dei falsi positivi, poiché _ è un jolly in query come SQL. –

+0

@FrankSchmitt risposta aggiornata – pudaykiran

Problemi correlati