When using Firebird with Spring Boot, sometimes JPA methods are not enough. Native queries give you more control over SQL execution while still using JPA.
Add Dependencies
In
pom.xml:
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk18</artifactId>
<version>5.0.3.java18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Configure Firebird
application.properties:
spring.datasource.url=jdbc:firebirdsql://localhost:3050/yourdb
spring.datasource.username=sysdba
spring.datasource.password=masterkey
spring.datasource.driver-class-name=org.firebirdsql.jdbc.FBDriver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.FirebirdDialect
Create Entity
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
// getters and setters
}
Repository with Native Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM users WHERE username = ?1", nativeQuery = true)
User findByUsername(String username);
@Query(value = "SELECT * FROM users WHERE email LIKE %?1%", nativeQuery = true)
List<User> searchByEmail(String emailPart);
}
Service Layer
@Service
public class UserService {
@Autowired
private UserRepository repo;
public User getByUsername(String username) {
return repo.findByUsername(username);
}
public List<User> searchByEmail(String email) {
return repo.searchByEmail(email);
}
}
Controller
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService service;
@GetMapping("/username/{name}")
public User getByUsername(@PathVariable String name) {
return service.getByUsername(name);
}
@GetMapping("/email/{part}")
public List<User> searchByEmail(@PathVariable String part) {
return service.searchByEmail(part);
}
}
image quote pre code