Looking to fetch entities with null
fields using Spring Data JPA? Whether you need all such entities or just the first one, itβs super clean with method naming conventions.
π 1. Fetch All Where Field Is null
Suppose you have a User
entity with an email
field, and you want all users where email
is null
.
π§± Entity Class
java
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
π Repository Interface
java
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAllByEmailIsNull();
}
π§ Service Example
java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsersWithNullEmail() {
return userRepository.findAllByEmailIsNull();
}
}
π Controller Example
java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/null-email")
public List<User> getUsersWithNullEmail() {
return userService.getUsersWithNullEmail();
}
}
π― 2. Fetch Just One (First Match)
Use findFirstBy...IsNull()
for one result.
π Repository Interface
java
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findFirstByEmailIsNull();
}
π§ Service
java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Optional<User> getFirstUserWithNullEmail() {
return userRepository.findFirstByEmailIsNull();
}
}
π Controller
java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/first-null-email")
public Optional<User> getFirstUserWithNullEmail() {
return userService.getFirstUserWithNullEmail();
}
}
π Summary
GoalMethod NameReturn TypeGet all where field is nullfindAllBy<Field>IsNull()List<T>
Get one where field is nullfindFirstBy<Field>IsNull()Optional<T>
With Spring Data JPAβs query method naming, null checks are easyβno need to write JPQL manually.