Created
May 11, 2023 13:59
-
-
Save sachin-handiekar/1478e784c322bbf10a15e7b35f20a8b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User | |
Convert legacy Hibernate Criteria to Spring Boot JPA | |
ChatGPT | |
Hibernate Criteria is a way of building dynamic queries in Hibernate using Java code. JPA (Java Persistence API) is a specification that defines a set of Java interfaces for accessing relational databases. Spring Boot provides a JPA implementation, which makes it easier to work with relational databases in a Spring Boot application. | |
Here's an example of how to convert a Hibernate Criteria query to Spring Boot JPA: | |
Hibernate Criteria query: | |
java | |
Copy code | |
Session session = sessionFactory.openSession(); | |
Criteria criteria = session.createCriteria(Person.class); | |
criteria.add(Restrictions.eq("firstName", "John")); | |
criteria.add(Restrictions.eq("lastName", "Doe")); | |
List<Person> persons = criteria.list(); | |
Spring Boot JPA query: | |
java | |
Copy code | |
public interface PersonRepository extends JpaRepository<Person, Long> { | |
List<Person> findByFirstNameAndLastName(String firstName, String lastName); | |
} | |
In the Spring Boot JPA example, we're using Spring Data JPA's repository abstraction to define a method that finds all persons with a given first and last name. Spring Data JPA automatically generates the necessary SQL query based on the method name and parameters. | |
To use the PersonRepository in your code, you can autowire it into a Spring component or service: | |
java | |
Copy code | |
@Service | |
public class PersonService { | |
@Autowired | |
private PersonRepository personRepository; | |
public List<Person> getPersonsByName(String firstName, String lastName) { | |
return personRepository.findByFirstNameAndLastName(firstName, lastName); | |
} | |
} | |
This PersonService class uses the PersonRepository to retrieve a list of persons with a given first and last name. This is a simple example, but you can use Spring Data JPA to define more complex queries as well. | |
User | |
show me a complex query | |
ChatGPT | |
Sure, here's an example of a more complex query using Spring Data JPA: | |
Suppose we have an entity class Product with the following fields: | |
java | |
Copy code | |
@Entity | |
public class Product { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String name; | |
private BigDecimal price; | |
@ManyToOne | |
@JoinColumn(name = "category_id") | |
private Category category; | |
// getters and setters | |
} | |
And an entity class Category with the following fields: | |
java | |
Copy code | |
@Entity | |
public class Category { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String name; | |
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) | |
private List<Product> products = new ArrayList<>(); | |
// getters and setters | |
} | |
We want to find all products that belong to a category with a given name and whose price is less than a certain amount, sorted by price in descending order. | |
Here's how we can define the method in a ProductRepository interface using Spring Data JPA: | |
java | |
Copy code | |
public interface ProductRepository extends JpaRepository<Product, Long> { | |
List<Product> findByCategoryNameAndPriceLessThanOrderByPriceDesc(String categoryName, BigDecimal price); | |
} | |
This method will automatically generate the following SQL query: | |
sql | |
Copy code | |
SELECT * FROM product p | |
INNER JOIN category c ON p.category_id = c.id | |
WHERE c.name = ? AND p.price < ? | |
ORDER BY p.price DESC | |
To use this query, we can simply call the method in our service or controller: | |
java | |
Copy code | |
@Service | |
public class ProductService { | |
@Autowired | |
private ProductRepository productRepository; | |
public List<Product> getProductsByCategoryAndPrice(String categoryName, BigDecimal maxPrice) { | |
return productRepository.findByCategoryNameAndPriceLessThanOrderByPriceDesc(categoryName, maxPrice); | |
} | |
} | |
This is just one example of a complex query using Spring Data JPA. Spring Data JPA provides many other ways to define queries, such as using JPQL (Java Persistence Query Language), Criteria API, or native SQL. | |
User | |
show me an example using Criteria API | |
ChatGPT | |
Sure, here's an example of a query using the Criteria API in Spring Data JPA: | |
Suppose we have an entity class Order with the following fields: | |
java | |
Copy code | |
@Entity | |
public class Order { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
@ManyToOne | |
@JoinColumn(name = "customer_id") | |
private Customer customer; | |
private LocalDateTime date; | |
private BigDecimal total; | |
// getters and setters | |
} | |
And an entity class Customer with the following fields: | |
java | |
Copy code | |
@Entity | |
public class Customer { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String firstName; | |
private String lastName; | |
@OneToMany(mappedBy = "customer") | |
private List<Order> orders = new ArrayList<>(); | |
// getters and setters | |
} | |
We want to find all orders placed by a customer with a given first and last name, ordered by date in descending order. | |
Here's how we can define the method in a OrderRepository interface using Criteria API: | |
java | |
Copy code | |
public interface OrderRepository extends JpaRepository<Order, Long> { | |
List<Order> findAllByCustomerFirstNameAndCustomerLastNameOrderByDateDesc(String firstName, String lastName); | |
} | |
To implement this method using the Criteria API, we need to create a CriteriaQuery and add Predicates to filter the results based on the customer's first and last name. We can also add an Order to sort the results by date in descending order. | |
java | |
Copy code | |
public interface OrderRepository extends JpaRepository<Order, Long> { | |
default List<Order> findAllByCustomerFirstNameAndCustomerLastNameOrderByDateDesc(String firstName, String lastName) { | |
CriteriaBuilder builder = entityManager().getCriteriaBuilder(); | |
CriteriaQuery<Order> query = builder.createQuery(Order.class); | |
Root<Order> root = query.from(Order.class); | |
Join<Order, Customer> customerJoin = root.join("customer"); | |
Predicate firstNamePredicate = builder.equal(customerJoin.get("firstName"), firstName); | |
Predicate lastNamePredicate = builder.equal(customerJoin.get("lastName"), lastName); | |
query.where(builder.and(firstNamePredicate, lastNamePredicate)) | |
.orderBy(builder.desc(root.get("date"))); | |
return entityManager().createQuery(query).getResultList(); | |
} | |
} | |
In this implementation, we use the CriteriaBuilder to create a CriteriaQuery for Order objects. We then create a Root object representing the Order entity and a Join object representing the Customer entity. We add Predicates to filter the results based on the customer's first and last name, and we add an Order to sort the results by date in descending order. | |
To use this query, we can simply call the method in our service or controller: | |
java | |
Copy code | |
@Service | |
public class OrderService { | |
@Autowired | |
private OrderRepository orderRepository; | |
public List<Order> getOrdersByCustomerName(String firstName, String lastName) { | |
return orderRepository.findAllByCustomerFirstNameAndCustomerLastNameOrderByDateDesc(firstName, lastName); | |
} | |
} | |
This is just one example of a query using the Criteria API in Spring Data JPA. The Criteria API provides a powerful way to build dynamic queries using Java code. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment