0

I have a problem with my little WebApp.

I can't delete/add/edit my cars after I add SQL connect. What is wrong in here? I am entry level so please explain me straight what the problem is.

  package com.RentCar.Rent_A_car.domain;

    import javax.persistence.*;

@Entity
public class Car {


//    @Id
//    @GeneratedValue(strategy = GenerationType.AUTO)
//    //int id;
    String mark;
    @Id
    String plate;
    int mileage;

    @OneToOne
    public Errand errand;

    public Car() { }

    public Car(String mark, String plate, int mileage) {
        this.mark = mark;
        this.plate = plate;
        this.mileage = mileage;

    }


    public void setErrand(Errand errand) {
        this.errand = errand;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public String getPlate() {
        return plate;
    }

    public void setPlate(String plate) {
        this.plate = plate;
    }

    public int getMileage() {
        return mileage;
    }

    public void setMileage(int mileage) {
        this.mileage = mileage;
    }

    public Errand getErrand() {
        return errand;
    }

    /*
        To jest sposób na wstryzkiwanie przez metodę


         */
    //    public Car(String mark, String plate, int mileage) {
//        this.mark = mark;
//        this.plate = plate;
//        this.mileage = mileage;
//    }
//
    @Override
    public String toString() {
        // dodać czy jest uszkodzone, stoi na parkingu, jest u mechanika
        if(errand == null){
            return "Car " + mark + ". Plate number: " + plate + ". Milage: " + mileage +
                    ". Errand of car : Car have no errand";
        } else {
            return "Car " + mark + ". Plate number: " + plate + ". Milage: " + mileage +
                    ". Current errand: " + errand;
        }
    }
}

This is my CarRepo class

    enter code here
    package com.RentCar.Rent_A_car.domain.Repository;

import com.RentCar.Rent_A_car.domain.Car;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class CarsRepository {

    // class to do CRUD operation on cars and errands

    Map<String, Car> CarList = new HashMap<>();

    @PersistenceContext
    private EntityManager em;



    @Transactional
    public void AddCar (String mark, String plate, int mileage){
        Car newCar = new Car(mark, plate, mileage);
        em.persist(newCar);

    }
     //pobiera aktualne id i dodaje do mapy
    public void AddCar(Car car) {
        em.persist(car);

    }

    // dla każdego "powyzej" usuniętego trzeba zmniejszyć id o 1 ; pętla o dlugosci pozostałych    aut id--; KONIECZNE FINALNIE, do budowy nie
    @Transactional
    public void DellateCar(String plate){
        em.remove(plate);

    }


    public Car getCar(String plate){

        Car car = em.createQuery("from Car c where c.plate=:plate", Car.class)
                .setParameter("plate", plate).getSingleResult();
        return car;
    }

    public Collection<Car> getAllCars() {
        return em.createQuery("from Car",Car.class).getResultList();

    }
    @Transactional
    public void updateCar(Car car) {
        em.merge(car);
    }

//    public String getPlate() {
//        if (CarList.isEmpty()) {
//            return "Car list is empty";
//        } else {
//            return (String)CarList.keySet();
//        }
//    }

//    @PostConstruct
//    public void build() {
//        AddCar("BMW","DW",100000);
//        AddCar("Opel","DTR",100043);
//        AddCar("Toyota","WB",1012300);
//        AddCar("Audi","DST",102340);
//
//    }


    @Override
    public String toString() {

        return "CarsRepository{" +
                "CarList="  +
                '}' + "\n";
    }



}

and this is my controller class

   package com.RentCar.Rent_A_car.domain.Controllers;

import com.RentCar.Rent_A_car.domain.Car;
import com.RentCar.Rent_A_car.domain.Repository.CarsRepository;
import com.RentCar.Rent_A_car.domain.Services.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.transaction.Transactional;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;

@Controller
    public class CarController {

// nie powinno się komunikować między bazą danych a kontrolerem, pomiędzy powinien być serwis.
@Autowired
CarService carService;


@RequestMapping("/cars")
public String getCars(Model model) {
    List<Car> CarList = carService.getAllCars();
    model.addAttribute("cars", CarList);
    return "cars";
}

@RequestMapping("/newcar")
public String newCar(Model model) {
    model.addAttribute("car", new Car());
    return "newcar";
}

// W TYM WYPADKU KOMUNIKACJA IDZIE OD KLIENTA, W atrybucie podajemy co otrzymujemy ( nmowe auto)
@RequestMapping(value = "/cars", method = RequestMethod.POST)
public String saveCar(Car car) {
    carService.saveCar(car);
    return "redirect:/cars";
}

//pobieranie parametru z adresu URL
@RequestMapping("/car")
public String getCar(@RequestParam("plate") String plate, Model model) {
    Car car = carService.getCar(plate);
    model.addAttribute("car", car);
    return "car";
}

@RequestMapping(value = "/car/delete/{plate}")
@Transactional
public String deleteCar(@PathVariable("plate") String plate, Model model) {
    carService.deleteCar(plate);
    return "redirect:/cars";
}
}

Please, I cant find what the problem is. For example if for delete, what is wrong? Maybe the problem is in templates?

2
  • What's the exact error message (including stack trace) which you get? Commented Nov 11, 2020 at 7:04
  • "I am entry level" - so maybe you shouldn't start with "a little web app" including complex frameworks like Spring and Hibernate? Commented Nov 11, 2020 at 9:17

1 Answer 1

2

The problem is in here:

public void DellateCar(String plate){
    em.remove(plate);
}

You have to pass the managed Car object or a reference to it, not some obscure string.

public void DellateCar(String plate){
    Car c = em.getReference(Car.class, plate); // or em.find(Car.class, plate);
    em.remove(c);
}

You can use getReference(entityclass, id) when you merely plan on deleting the object, so you don't actually go through the trouble of loading it from the database. Otherwise use find(entityclass, id)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.