0% found this document useful (0 votes)
18 views8 pages

Scribd

The document discusses using Spring Data JPA and Spring Data JDBC to interact with relational databases. Spring Data provides abstractions and repositories that simplify common data access tasks. Entities can be mapped to database tables using annotations and CRUD operations are available on repository interfaces.

Uploaded by

Daniel Alex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

Scribd

The document discusses using Spring Data JPA and Spring Data JDBC to interact with relational databases. Spring Data provides abstractions and repositories that simplify common data access tasks. Entities can be mapped to database tables using annotations and CRUD operations are available on repository interfaces.

Uploaded by

Daniel Alex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Spring Boot care expune Rest API

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;
}

// Getters and setters


}

@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);
}
}

public interface FoodRepository extends JpaRepository<Food, Long> {


@Query("SELECT f from Food f WHERE f.locatie =:locatie")
List<Food> findByLocatie(String locatie);

@Query("SELECT f from Food f WHERE f.date=:data_specificata")


List<Food> findByDate(LocalDate data_specificata);
}

@ResponseStatus(HttpStatus.NOT_FOUND)
public class FoodNotFoundException extends RuntimeException {
public FoodNotFoundException(String message) {
super(message);
}
}

-----------------------------------------------------------------------------------
---

Proiect Web Dinamic Spring Boot. Sprin Data JPA

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;

public Food(String id, String name, String category) {


super();
this.id = id;
this.name = name;
this.category = category;
}

// Getters and setters


}

@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";
}
}

public interface FoodRepository extends JpaRepository<Food, String> {


@Query("SELECT f FROM Food f WHERE f.category = :category")
public List<Food> filterByCategory(String category);
}

<!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}"/>

<table class="table table-striped table-bordered">


<tr>
<th>ID</th>
<th>Name</th>
<th>Category</th>
</tr>
<tr th:each="f : ${lista}">
<td th:text="${f.getId()}"></td>
<td th:text="${f.getName()}"></td>
<td th:text="${f.getCategory()}"></td>
</tr>
</table>

<form th:action="@{/Adauga}" method="post">


<input type="text" name="id" placeholder="ID..." size="46" required/>
<input type="text" name="name" placeholder="Name..." size="46" required/>
<input type="text" name="category" placeholder="Category..." size="46"
required/>
<button class="btn btn-lg btn-secondary" type="submit">Adauga</button>
</form>

<form th:action="@{/Modifica}" method="post">


<input type="text" name="id" placeholder="ID..." size="46" required/>
<input type="text" name="name" placeholder="Name..." size="46"/>
<input type="text" name="category" placeholder="Category..." size="46"/>
<button type="submit" class="btn btn-lg btn-primary">Modifica</button>
</form>

<form th:action="@{/Delete}" method="post">


<input type="text" name="id" placeholder="ID..." size="46" required/>
<button type="submit" class="btn btn-lg btn-danger">Delete</button>
</form>

<form th:action="@{/Filtrare}" method="get">


<input type="text" name="category" placeholder="Category..." size="46"
required/>
<button type="submit" class="btn btn-lg btn-secondary">Filtreaza dupa
category</button>
</form>

</body>
</html>

-----------------------------------------------------------------------------------
-----

Spring Boot. Spring Data JDBC

Spring Data JDBC has the following features:

Automatically manages the opening and closing of database connections.


Encourages the use of DAO (Data Access Object) objects for data access management,
thus allowing a clear separation between application code and database access
logic.
Provides support for managing transactions using annotations without the need for
additional code to start a transaction.
Offers support for mapping data from tables to objects or lists of objects.
JdbcTemplate is a central class in Spring Data JDBC that provides simplified
methods for executing SQL commands, managing transactions, and handling results.

public class Food {


private int id;
private String name;
private String category;
private int expirationYear;
private String color;
private int calories;

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;
}

// Getters and setters


}

@Repository
public class FoodJdbcDao {
@Autowired
JdbcTemplate jdbcTemplate;

public List<Food> findAll() {


String sql = "select * from foods";
return jdbcTemplate.query(sql, new FoodMapper());
}

public Food findById(int id) {


String sql = "select * from foods where id=?";
return jdbcTemplate.queryForObject(sql, new FoodMapper(), id);
}

public int deleteById(int id) {


String sql = "delete from foods where id=?";
return jdbcTemplate.update(sql, id);
}

public int insert(Food food) {


String sql = "insert into foods values(?,?,?,?,?,?)";
return jdbcTemplate.update(sql, food.getId(), food.getName(),
food.getCategory(), food.getExpirationYear(), food.getColor(), food.getCalories());
}

public int update(Food food) {


String sql = "update foods set name=?, category=?, expiration_year=?,
color=?, calories=? where id=?";
return jdbcTemplate.update(sql, food.getName(), food.getCategory(),
food.getExpirationYear(), food.getColor(), food.getCalories(), food.getId());
}

public Food findByCategory(String category) {


String sql = "select * from foods where category=?";
return jdbcTemplate.queryForObject(sql, new FoodMapper(), category);
}

public List<Food> findRecentFoods() {


String sql = "select * from foods where expiration_year > ?";
return jdbcTemplate.query(sql, new FoodMapper(), 2020);
}

public int countLowCalorieFoods() {


String sql = "select COUNT(id) from foods where calories < 500";
return jdbcTemplate.queryForObject(sql, Integer.class);
}
}

public class FoodMapper implements RowMapper<Food> {


@Override
public Food mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Food(rs.getInt("id"), rs.getString("name"),
rs.getString("category"), rs.getInt("expiration_year"), rs.getString("color"),
rs.getInt("calories"));
}
}

@SpringBootApplication
public class FoodsApplication implements CommandLineRunner {
@Autowired
FoodJdbcDao dao;

public static void main(String[] args) {


SpringApplication.run(FoodsApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
System.out.println("\nAll foods:");
dao.findAll().forEach(System.out::println);

System.out.println("\nFood with id 1: " + dao.findById(1));

System.out.println("\nDelete food with id 1, number of rows deleted: " +


dao.deleteById(1));

System.out.println("\nAdd food with id 1, number of rows added: " +


dao.insert(new Food(1, "Apple", "Fruit", 2025, "Red", 95)));

System.out.println("\nUpdate food with id 1, number of rows updated: " +


dao.update(new Food(1, "Banana", "Fruit", 2024, "Yellow", 105)));

System.out.println("\nAll foods after addition, update, deletion:");


dao.findAll().forEach(System.out::println);

System.out.println("\nFood with category 'Fruit': " +


dao.findByCategory("Fruit"));

System.out.println("\nNumber of foods with calories < 500: " +


dao.countLowCalorieFoods());
}
}
drop table if exists foods;
create table foods (
id integer not null primary key,
name varchar(40) not null,
category varchar(40),
expiration_year int,
color varchar(20),
calories int
);
insert into foods (id, name, category, expiration_year, color, calories) values (1,
'Apple', 'Fruit', 2025, 'Red', 95);
insert into foods (id, name, category, expiration_year, color, calories) values (2,
'Carrot', 'Vegetable', 2023, 'Orange', 25);
insert into foods (id, name, category, expiration_year, color, calories) values (3,
'Beef', 'Meat', 2022, 'Brown', 250);
insert into foods (id, name, category, expiration_year, color, calories) values (4,
'Milk', 'Dairy', 2022, 'White', 150);
insert into foods (id, name, category, expiration_year, color, calories) values (5,
'Banana', 'Fruit', 2024, 'Yellow', 105);

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

You might also like