Following example shows how to use IS NULL to find properties values which have not been set.
Example
Entity
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String name;
private String dept;
private long salary;
.............
}
Using IS NULL
public class ExampleMain {
private static EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("example-unit");
public static void main(String[] args) {
try {
persistEmployees();
findEmployeeByDeptNull();
findEmployeeByDeptNotNull();
} finally {
entityManagerFactory.close();
}
}
public static void persistEmployees() {
Employee employee1 = Employee.create("Diana", "IT", 3000);
Employee employee2 = Employee.create("Rose", "Sales", 2000);
Employee employee3 = Employee.create("Denise", "Admin", 4000);
Employee employee4 = Employee.create("Mike", null, 3500);
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
em.persist(employee1);
em.persist(employee2);
em.persist(employee3);
em.persist(employee4);
em.getTransaction().commit();
em.close();
}
private static void findEmployeeByDeptNull() {
System.out.println("-- Employees with dept is NULL --");
EntityManager em = entityManagerFactory.createEntityManager();
Query query = em.createQuery(
"SELECT e FROM Employee e WHERE e.dept IS NULL");
List<Employee> resultList = query.getResultList();
resultList.forEach(System.out::println);
em.close();
}
private static void findEmployeeByDeptNotNull() {
System.out.println("-- Employees with dept is NOT NULL --");
EntityManager em = entityManagerFactory.createEntityManager();
Query query = em.createQuery(
"SELECT e FROM Employee e WHERE e.dept IS NOT NULL");
List<Employee> resultList = query.getResultList();
resultList.forEach(System.out::println);
em.close();
}
} -- Employees with dept is NULL -- Employee{id=4, name='Mike', dept='null', salary=3500} -- Employees with dept is NOT NULL -- Employee{id=1, name='Diana', dept='IT', salary=3000} Employee{id=2, name='Rose', dept='Sales', salary=2000} Employee{id=3, name='Denise', dept='Admin', salary=4000}
Example ProjectDependencies and Technologies Used: - h2 1.4.197: H2 Database Engine.
- hibernate-core 5.2.13.Final: The core O/RM functionality as provided by Hibernate.
Implements javax.persistence:javax.persistence-api version 2.1 - JDK 1.8
- Maven 3.3.9
|
|