Поля, помеченные аннотацией @Transient, не устанавливаются для одного и того же объекта в Spring Boot - PullRequest
0 голосов
/ 21 января 2019

Поля Non-Transient JPA не отражаются для объекта.

Театр Сущность класс: -

@Entity(name = "Theatre")
public class Theatre {

    Theatre() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private long id;
    @Column(name = "name")
    @NotNull
    private String name;
    @Column(name = "address")
    @NotNull
    private String address;
    @Column(name = "city")
    @NotNull
    private String city;
    @Column(name = "is_active")
    @NotNull
    private Boolean isactive;

    public List<TheatreHall> getHalls() {
        return halls;
    }

    public void setHalls(List<TheatreHall> halls) {
        this.halls = halls;
    }

    //@Column(name="halls")
    //@OneToMany(mappedBy="theatre", cascade = CascadeType.ALL)
    @Transient
    //@JsonIgnore
    private List<TheatreHall> halls;
    @Transient
    @JsonIgnore
    private Map<Movie, LinkedList<Time>> map;

    //@JsonProperty(value="is_active")

    public Boolean getIsactive() {
        return isactive;
    }

    public void setIsactive(Boolean isactive) {
        this.isactive = isactive;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Map<Movie, LinkedList<Time>> getMap() {
        return map;
    }

    public void setMap(Map<Movie, LinkedList<Time>> map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "Theatre{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", city='" + city + '\'' +
                ", isactive=" + isactive +
                ", halls=" + halls +
                ", map=" + map +
                '}';
    }

}

Театральный контроллер: -

@RestController
public class TheatreController {

    @Autowired
    private MovieRepository movierepository;
    @Autowired
    private TheatreRepository theatrerepository;

    @RequestMapping(value = "/getactivetheatres", method = RequestMethod.GET)
    public ResponseEntity getActiveTheatres(@RequestParam String city) {

        return new ResponseEntity(theatrerepository.findActiveTheatresByCity(city)
                ,
                HttpStatus.OK);
    }

    @RequestMapping(value = "/addtheatre", method = RequestMethod.POST)
    public HttpStatus addTheatre(@Valid @RequestBody Theatre theatre) {

        theatrerepository.save(theatre);
        //List<TheatreHall> list = new LinkedList<TheatreHall>();
        //theatre.setHalls(list);
        return HttpStatus.CRETED;

    }

    @RequestMapping(value = "/addtheatrehall", method = RequestMethod.PUT)
    public HttpStatus addHall(@RequestParam(value = "theatreid") long theatreid, @RequestBody TheatreHall theatreHall) {

        Theatre theatre = theatrerepository.findById(theatreid);
        System.out.println(theatre);
        if (theatre.getHalls() == null) {
            theatre.setHalls(new LinkedList<TheatreHall>());
        }
        theatre.getHalls().add(theatreHall);
        theatrerepository.save(theatre);
        System.out.println(theatre);
        return HttpStatus.ACCEPTED;

    }

    @RequestMapping(value = "/addmovie", method = RequestMethod.POST)
    public HttpStatus addMovie(@RequestParam(value = "theatreid") long theatreid, @RequestParam(value = "movieid") long movieid) {

        Theatre theatre = theatrerepository.findById(theatreid);
        Movie movie = movierepository.findMovieById(movieid);

        System.out.println(theatre);
        System.out.println(movie);
        for (TheatreHall hall : theatre.getHalls()) {
            if (hall.getMovie() == null) {
                hall.setMovie(movie);
                return HttpStatus.ACCEPTED;
            }

        }
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "All halls are occupied");
    }
}

Театральный зал: -

public class TheatreHall {
    private Theatre theatre;
    private Byte hallid;
    private Byte rows;
    private Byte columns;
    private boolean is_active;
    private Movie movie;
    private int vacant_seats;
    private boolean arr[][];
    Map<Byte, Byte> vacantseatscount;

    TheatreHall() {

    }

    TheatreHall(Byte hallid, Byte rows, Byte columns) {
        this.hallid = hallid;
        this.rows = rows;
        this.columns = columns;
        this.arr = new boolean[rows][columns];
        vacant_seats = rows * columns;
        vacantseatscount = new LinkedHashMap<Byte, Byte>();
        for (Byte i = 0; i < rows; i++) {
            vacantseatscount.put(i, columns);
        }
    }
}

TheatreHall также содержит сеттеры и геттеры, которые я здесь не добавил для сокращения кода.

Теперь проблема, с которой я сталкиваюсь, заключается в том, что когда я вызываю конечную точку /addtheatrehall, зал подключается к театру, а когда я печатаю объект театра на том же контроллере, театральные отражения отражаются как ненулевые.

Когда я вызываю конечную точку /addtheatrehall, я получаю исключение нулевого указателя, и объект театра, напечатанный в журналах, показывает, что значение залов для этого театра равно нулю.

1 Ответ

0 голосов
/ 22 января 2019

Из того, что я могу разглядеть в вашем коде, вы устанавливаете private List<TheatreHall> halls; как @Transient, который помечает его как игнорируемый при сохранении в базе данных, следовательно, он всегда равен нулю.

...