2

I want to write this SQL statement in eclipse JPQL query. It works in SQL but I'm not sure how to write it in eclipse.

SELECT * 
FROM hardware h
WHERE h.`Staffid` LIKE '%150%'

My staffid in hardware table is a foreign key to staff table's staffid primary key. So the staff in the hardware table is

private Staff staff;

This is what I write to run my search:

@SuppressWarnings("unchecked")
public List<Hardware> searchstaff(Staff a) {
    try {
        entityManager.getTransaction().begin();             

        Query query = entityManager
            .createQuery("SELECT st from Hardware st where st.staff LIKE :x");
        query.setParameter("x", a);

        List<Hardware> list = query.getResultList(); 
        entityManager.getTransaction().commit();         
        return list;                     
    } catch (Exception e) {
        return null;
    }
}

But it shows

javax.servlet.ServletException: java.lang.IllegalStateException: 
Exception Description: Transaction is currently active 

when I run the search.

Can anyone help me correct?

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
yoko
  • 31
  • 1
  • 3

1 Answers1

5

The like operator work only with string. So do something like that:

Query query = entityManager
    .createQuery("SELECT st from Hardware st where st.staff.id LIKE :x");
query.setParameter("x", '%' + a.getId() + '%');

Link :

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122