修改像这样的弹簧数据结果查询是一个好习惯吗?

时间:2018-02-08 14:17:56

标签: java spring spring-data-jpa

我希望你对我使用的练习有所了解,我不认为它很干净。

这个想法是根据需求添加一个字段,所以非持久性。 我留下了一个车库的例子,车库里有几辆不同品牌和颜色的车。请求必须显示车库中的所有车辆,如果颜色与请求的颜色相符,则计算字段“作为选定颜色”必须显示 true或false ,如此示例中所示:

{
    "cars": [
        {
            "color": "red",
            "brand": "opel",
            "garage": {
                "name": "Garage1"
            },
            HERE => "as selected color": true
        },
        {
            "color": "black",
            "brand": "bmw",
            "garage": {
                "name": "Garage1"
            },
            HERE => "as selected color": false
        },
        {
            "color": "red",
            "brand": "fiat",
            "garage": {
                "name": "Garage1"
            },
            HERE => "as selected color": true
        },
        ...
    ]
}

要获得由OneToMany关系链接的两个实体的信息组成的结果,我使用像这样的对象列表:

@PostMapping("/list")
public ResponseEntity<HashMap> process(@RequestBody Map<String, String> request) throws Exception {
...    
    List<Object> garageWithCars = new ArrayList<Object>();
    garageWithCars = garageRepository.findCars();

    // Set if color is same as asked
    // Is it a good practice ?
    for (Object tempObject : garageWithCars) {
        if (tempObject.getClass() == Car.class) {
            ((Car)tempObject).setIsSelectedColor(color);
        }
    }

    map.put("List", garageWithCars);
    return new ResponseEntity<HashMap>(map, HttpStatus.OK);
}

在我看来这不是非常亲,所以我希望你对这种做法有所了解,谢谢。

这是 GarageRepository

@Repository
public interface GarageRepository  extends JpaRepository<Garage,Long> {
    @Query("select c from Car as c")
    List<Object> findCars();
}

汽车类:

@Entity
@Table(name = "car")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "car_id")
    @JsonIgnore
    private Long id;

    @Column(name = "color")
    String color;

    @Column(name = "brand")
    String brand;

    @Transient
    @JsonProperty("as selected color")
    Boolean isSelectedColor = false;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="garage_id", nullable = false)
    private Garage garage;

    Car() {}

    public Boolean getIsSelectedColor() {
        return isSelectedColor;
    }

    public void setIsSelectedColor(String selectedColor) {
        if(color.equalsIgnoreCase(selectedColor)) {
            this.isSelectedColor = true;
        }
    }
    ... getters and setters
}

车库类:

@Entity
@Table(name="garage")
public class Garage {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "garage_id")
    @JsonIgnore
    private Long id;

    @Column(name="name")
    private String name;

    @OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.LAZY,
            mappedBy = "garage")
    @JsonBackReference
    private Set<Car> cars = new HashSet<>();

    public Garage() {}

    ... getters and setters
}

0 个答案:

没有答案