Skip to content
Advertisement

Using BETWEEN in native query in JPQL

I tried to make a query using BETWEEN in JPQL, I already tested it in SQL and it works, but when I implemented in JPQL I got an error:

Caused by: javax.persistence.PersistenceException: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): 
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: 
Incorrect syntax near ':'.
Error Code: 102"

I don’t understand why there is the error near :, can anybody help me figure it out?

Here is my code:

public List<Object[]> reportPendapatan(String tahun) {
    String tahun1 = tahun +"-01-01";
    String tahun2 = tahun +"-12-31";
    return em.createNativeQuery("SELECT p.tanggal, m.nama, pg.nama_jenis, g.nama_guru,pg.harga_masuk FROM Pendaftaran p, Murid m, pengajian pg, Guru g  WHERE p.id_murid = m.id_murid and p.tanggal between :tahun and :tahun2 and p.id_guru = g.id_guru and p.id_jenis = pg.id_jenis and p.status=4")       
            .setParameter("tahun", tahun1)
            .setParameter("tahun2", tahun2)
            .getResultList(); 
}

Advertisement

Answer

According to this answer, EclipseLink has slightly different syntax of setting named parameters in native queries using ? prefix instead of :

public List<Object[]> reportPendapatan(String tahun) {
    String tahun1 = tahun +"-01-01";
    String tahun2 = tahun +"-12-31";
    return em.createNativeQuery(
        "SELECT p.tanggal, m.nama, pg.nama_jenis, g.nama_guru,pg.harga_masuk "
        + "FROM Pendaftaran p, Murid m, pengajian pg, Guru g "
        + "WHERE p.id_murid = m.id_murid and p.tanggal between ?tahun and ?tahun2 "
        + "and p.id_guru = g.id_guru and p.id_jenis = pg.id_jenis and p.status=4")
        .setParameter("tahun", tahun1)
        .setParameter("tahun2", tahun2)
        .getResultList(); 
}

Other option is to use positional parameters 1 and 2 for tahun1 and tahun2 respectively:

    // ...
    return em.createNativeQuery(
        "SELECT p.tanggal, m.nama, pg.nama_jenis, g.nama_guru,pg.harga_masuk "
        + "FROM Pendaftaran p, Murid m, pengajian pg, Guru g "
        + "WHERE p.id_murid = m.id_murid and p.tanggal between ? and ? "
        + "and p.id_guru = g.id_guru and p.id_jenis = pg.id_jenis and p.status=4")
        .setParameter(1, tahun1)
        .setParameter(2, tahun2)
        .getResultList(); 

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement