Query Language (Native Query BiQL) - bobocode-breskul/bibernate GitHub Wiki

Retrieving Entities with SQL and BiQL

The Bibernate framework allows you to retrieve entities based on data from the database through queries written in the standard SQL (Structured Query Language), as well as the simplified BiQL (Bibernate Query Language). To use this functionality, objects of the Session class have the executeNativeQuery and executeBiQLQuery methods, respectively. These methods return a List that is parameterized by the type of entity that is passed as the second parameter. If necessary, you can get a single entity by processing the resulting list in the required way.

SQL Queries

SQL supports "select" queries. To use this feature, you need to call the executeNativeQuery(String sqlString, Class<T> resultClass) method on an object of type Session, passing it a string with a SQL query as the first parameter (for example, "select * from persons where age > 30"), and the entity class as the second parameter (for example, Person.class).

Code Examples for SQL:

List<Photo> photos = session.executeNativeQuery("select * from photo", Photo.class);
List<Photo> photos = session.executeNativeQuery("select * from photo p", Photo.class);
List<Photo> photos = session.executeNativeQuery("select * from photo p where p.id = 5", Photo.class);
List<Photo> photos = session.executeNativeQuery("select * from photo p limit 1", Photo.class);

BiQL Queries

BiQL supports "select" queries with the following extensions: where, order by, limit, offset. To use this feature, you need to call the executeNativeQuery(String sqlString, Class<T> resultClass) method on an object of type Session, passing it a string with a BiQL query as the first parameter (for example, "select p from Person p where p.age > 30"), and an entity class as the second parameter (for example, Person.class).

Code Examples for BiQL:

List<Photo> photos = session.executeBiQLQuery("from Photo", Photo.class);
List<Photo> photos = session.executeBiQLQuery("select p from Photo p", Photo.class);
List<Photo> photos = session.executeBiQLQuery("select p from Photo p where p.id in (1, 3, 5)", Photo.class);
List<Photo> photos = session.executeBiQLQuery("select p from Photo p in order by p.id desc", Photo.class);

'select p' can be omitted.

Note that when selecting not all, but only a few fields from the database using SQL or BiQL, you must have a constructor created to initialize the object using the values of these fields.

⚠️ **GitHub.com Fallback** ⚠️