Scribd
Scribd
JPA provides a standardized way to perform the mapping from the relational model to
the object model (object relational mapping) and to interact with relational
databases using Java objects
JPA allows mapping Java classes to database tables, making it easier to work with
objects in Java code f
no more need to write SQL commands
Java classes can map to tables using annotations
Interaction with the database in JPA is done using the interface
EntityManager. It provides CRUD (Create, Read, Update, Delete) operations
JPA provides an object-oriented query language called JPQL, which is
similar to SQL, but unlike it works with classes
and properties do not
with tables
and necklaces
@Entity
@Table(name="foods")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
String denumire;
String locatie;
LocalDate date;
LocalTime ora;
float pret;
public Food(Long id, String denumire, String locatie, LocalDate date, LocalTime
ora, float pret) {
super();
this.id = id;
this.denumire = denumire;
this.locatie = locatie;
this.date = date;
this.ora = ora;
this.pret = pret;
}
@RestController
public class FoodController {
@Autowired
FoodRepository foodRepo;
@GetMapping("jpa/foods")
public List<Food> findAll(){
return foodRepo.findAll();
}
@GetMapping("jpa/foods/locatie/{denumire_locatie}")
public List<Food> findByLocatie(@PathVariable String denumire_locatie){
if(foodRepo.findByLocatie(denumire_locatie) != null)
return foodRepo.findByLocatie(denumire_locatie);
else{
throw new FoodNotFoundException("Nu exista food-uri in locatia: " +
denumire_locatie +"!");
}
}
@GetMapping("jpa/foods/data/{data_specificata}")
public List<Food> findByDate(@PathVariable LocalDate data_specificata){
if(foodRepo.findByDate(data_specificata)!=null)
return foodRepo.findByDate(data_specificata);
else{
throw new FoodNotFoundException("Nu exista food-uri pe data de:
"+data_specificata);
}
}
@PostMapping("jpa/foods")
public Food addFood(@RequestBody Food food){
return foodRepo.save(food);
}
@PutMapping("jpa/foods/{id}")
public Food updateFood(@PathVariable Long id, @RequestBody Food foodDetails){
Food food = foodRepo.findById(id).orElseThrow(() -> new
FoodNotFoundException("Food-ul cu id-ul: "+id+" nu exista!"));
food.setDenumire(foodDetails.getDenumire());
food.setLocatie(foodDetails.getLocatie());
food.setDate(foodDetails.getDate());
food.setOra(foodDetails.getOra());
food.setPret(foodDetails.getPret());
return foodRepo.save(food);
}
@DeleteMapping("jpa/foods/id/{valoare_id}")
public void deleteFood(@PathVariable Long valoare_id){
foodRepo.deleteById(valoare_id);
}
}
@ResponseStatus(HttpStatus.NOT_FOUND)
public class FoodNotFoundException extends RuntimeException {
public FoodNotFoundException(String message) {
super(message);
}
}
-----------------------------------------------------------------------------------
---
Spring Data JPA provides an additional abstraction layer over JPA, making it easier
and more efficient for developers to work with JPA.
Spring Data JPA simplifies the development of JPA applications by providing
support for repetitive operations.
If in the previous example we had multiple persistent classes whose data would be
saved in linked tables, we would need to have a repository for each persistent
class (entity). These repositories would be similar in content, the main difference
being that instead of the class Persoana, the name of the entity managed by the
repository would appear.
Spring Data JPA provides the JpaRepository<Entitate, Tip_cheie_primara>
interface, which offers predefined methods to simplify CRUD operations on JPA
entities, reducing the volume of repetitive operations.
@Entity
@Table(name="foods")
public class Food {
@Id
@Column(name = "id", unique = true)
String id;
String name;
String category;
@Controller
public class FoodController {
@Autowired
FoodRepository foodRepo;
@GetMapping("/lista-foods")
public String getAllFoods(Model model) {
String str = "Lista food-urilor preluate prin repository";
model.addAttribute("str", str);
model.addAttribute("lista", foodRepo.findAll());
return "foods";
}
@PostMapping("/Adauga")
public String addFood(@ModelAttribute Food food){
foodRepo.save(food);
return "redirect:/lista-foods";
}
@PostMapping("/Modifica")
public String updateFood(@ModelAttribute Food foodDetails){
String id = foodDetails.getId();
Food food = foodRepo.findById(id).orElseThrow(() -> new
RuntimeException("Food cu id: " + id + " nu a fost gasit!"));
food.setId(foodDetails.getId());
food.setName(foodDetails.getName());
food.setCategory(foodDetails.getCategory());
foodRepo.save(food);
return "redirect:/lista-foods";
}
@PostMapping("/Delete")
public String deleteFood(String id){
foodRepo.deleteById(id);
return "redirect:/lista-foods";
}
@GetMapping("/Filtrare")
public String filterByCategory(@RequestParam("category") String category, Model
model){
String str = "Lista cu food-urile din categoria dorita: ";
model.addAttribute("str", str);
List<Food> foodsByCategory = foodRepo.filterByCategory(category);
if(foodsByCategory == null){
throw new RuntimeException("Nu exista food-uri din categoria introdusa
de tine!");
} else {
model.addAttribute("lista", foodsByCategory);
}
return "foods";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<title>Lista Foods</title>
</head>
<body>
<h3 th:text="${str}"/>
</body>
</html>
-----------------------------------------------------------------------------------
-----
public Food(int id, String name, String category, int expirationYear, String
color, int calories) {
super();
this.id = id;
this.name = name;
this.category = category;
this.expirationYear = expirationYear;
this.color = color;
this.calories = calories;
}
@Repository
public class FoodJdbcDao {
@Autowired
JdbcTemplate jdbcTemplate;
@SpringBootApplication
public class FoodsApplication implements CommandLineRunner {
@Autowired
FoodJdbcDao dao;
@Override
public void run(String... args) throws Exception {
System.out.println("\nAll foods:");
dao.findAll().forEach(System.out::println);
spring.application.name=FoodsApp
spring.datasource.url=jdbc:mysql://localhost/food_db?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=mysqlpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.sql.init.mode=ALWAYS