AnimalServiceImpl.java
1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package fr.plil.sio.examen.services;
import fr.plil.sio.examen.api.Animal;
import fr.plil.sio.examen.api.Owner;
import fr.plil.sio.examen.repositories.AnimalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AnimalServiceImpl implements AnimalService {
@Autowired
private AnimalRepository animalRepository;
@Override
@Transactional
public Animal create(String name, Owner owner) {
if(name == null) {
throw new IllegalArgumentException("name must be not null");
}
if(owner == null) {
throw new IllegalArgumentException("owner must be not null");
}
Animal animal = new Animal();
animal.setName(name);
animal.setOwner(owner);
animalRepository.save(animal);
owner.getAnimals().add(animal);
return animal;
}
@Override
@Transactional
public void delete(Animal animal) {
if(animal==null){
throw new IllegalArgumentException("animal must be not null");
}
//Si on ne trouve pas d'animaux avec le meme nom alors il n'est pas en base de données
if(animalRepository.findByName(animal.getName()).size()==0){
//On lance donc une exception
throw new IllegalArgumentException("animal not in database");
}
//Enfin, on le supprime
animalRepository.delete(animal.getId());
animal.getOwner().getAnimals().remove(animal);
}
}