Spring Data JPA Examples: Querying Data by Json Properties in PostgresSql

NGU
2 min readMay 12, 2023

2 ways of Query data by Json’s property from a table with Json type column.

Talk is cheap. Just see the code.

init_Sql:

CREATE TABLE employee (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
data JSONB
);

Entity:

@Entity
@Getter
@Setter
@Table(name = "employee")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@Column(columnDefinition = "jsonb")
private String data;

}

Native SQL way Repository (way1):

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

@Query(value = "SELECT * FROM employee WHERE data->>'department' = ?1", nativeQuery = true)
List<Employee> findByDepartment(String department);
}

Specification way Repository (way2):

@Repository
public interface EmployeeSpecificationRepository extends JpaRepository<Employee, Long>, JpaSpecificationExecutor<Employee> {
}

Specification:

public class EmployeeSpecification {

public static Specification<Employee> hasDepartment(String department) {
return…

--

--

NGU

Microservices. Cloud Native. Architecture. Record Technology, Sports, Life. A picture is worth a thousand words