2

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(); 
}
1
  • What exactly is JSQL? Do you mean JPQL? Commented Sep 7, 2020 at 14:18

1 Answer 1

1

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(); 

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.