简体   繁体   中英

Convert SQL statement 'LIKE' to JPQL statement

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?

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 :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM