使用@Transactional时,其余服务未返回数据

时间:2018-07-22 14:32:24

标签: java spring rest spring-data-jpa h2

我创建了一个样本酒店预订应用程序 我有2种服务,一种是预订服务,另一种是用于查看预订,我正在使用内存DB H2。

当我尝试使用预订服务的预订URL预订房间时,发生预订(返回200 OK),但是当我使用@Transactional时未返回预订数据。如果我删除@Transactional(返回200 OK以及预订数据),它就可以正常工作

BookingServiceImpl

    package com.reservation.hotel.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.reservation.hotel.data.repositories.ReservationRepository;
import com.reservation.hotel.data.repositories.RoomRepository;
import com.reservation.hotel.domain.RoomReservation;
import com.reservation.hotel.domain.entities.Reservation;
import com.reservation.hotel.domain.entities.Room;
import com.reservation.hotel.service.BookingService;

@Service

public class BookingServiceImpl implements BookingService{

    @Autowired
    ReservationRepository reservationRepository;

    @Autowired
    RoomRepository roomRepository;

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
    private static final String getReservationsByGuestIdURL = "http://localhost:8088/hotel/reservations/guest/";

    @Transactional
    public List<RoomReservation> bookRoom(String roomId, String guestId, String date){
        //List<RoomReservation> reservations= new ArrayList<>();    


        //change status of booked room to true      
        Optional<Room> room = roomRepository.findById(Long.parseLong(roomId));      
        room.get().setBooked(true);     
        roomRepository.save(room.get());        

        Reservation reservation = new Reservation();

        reservation.setGuestId(Long.parseLong(guestId));
        reservation.setRoomId(Long.parseLong(roomId));
        reservation.setDate(new java.sql.Date(createDateFromDateString(date).getTime()));

        reservationRepository.save(reservation);

        RestTemplate restTemplate = new RestTemplate();

        return restTemplate.getForObject(getReservationsByGuestIdURL + guestId, List.class);

    }

    private Date createDateFromDateString(String dateString){
        Date date = null;
        if(null!=dateString) {
            try {
                date = DATE_FORMAT.parse(dateString);
            }catch(ParseException pe){
                date = new Date();
            }
        }else{
            date = new Date();
        }
        return date;
    }



}

@Transactional用于

时得到空响应
return restTemplate.getForObject(getReservationsByGuestIdURL + guestId, List.class);

您能解释一下这是怎么回事吗?

0 个答案:

没有答案