Creating multiple object with one response using S

2019-08-12 05:57发布

问题:

This is my first time using Spring to add and get data from a database. I have successfully established connection with my database and can add Plants with only id and plantName but now for the part that I do not understand.
How can I create an RowMapper or something else that would work with a loop that would get the Plant and go over all PlantParts to get me the object I need.
I should note that Plant is just an Object I created to ask here to keep it cleaner and easier to answer.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Plant {
    private Long id;
    private String plantName;
    private List<PlantParts> plantParts;

    public void add(PlantParts plantPartsObj) {
        if (plantParts == null) {
            plantParts = new ArrayList<>();
        }

        plantParts.add(plantPartsObj);
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PlantParts {
    private String leaves;
    private String pedicle;
    private String petals;
}

First I create a Plant object with this query:

INSERT INTO PLANTS (id, plantname)
  VALUES (NEXT VALUE FOR sequence, ?);

Then I add multiple PlantParts with this query:

INSERT INTO PLANT_PARTS (id, leaves, pedicle, petals)" +
                        "  VALUES (?, ?, ?, ?);

And now I am trying to make it all into one Plant object, but I do not get how I can get multiple PlantParts with one RowMapper.

And this would be my code using Spring:

@Repository
public class PlantDao {

    @Autowired
    private JdbcTemplate template;

    @Override
    public Order getPlantById(Long id) {
        String sql = "SELECT plants.id, plants.plantName, plant_parts.id, plant_parts.leaves, plant_parts.pedicle, plant_parts.petals " +
                "FROM plants " +
                "LEFT JOIN plant_parts ON plants.id = plant_parts.id AND plants.id = ?";

        return template.queryForObject(sql, new Object[] {id}, getPostRowMapper());

    }

    private RowMapper<Plant> getPostRowMapper() {
        return (rs, rowNum) -> new Plant(
                rs.getLong("id"),
                rs.getString("plantname")

                //Check if there are any PlantParts, if yes then go over
                //all of the PlantParts in a loop

        });
    }

Now the part that I do not understand is commented out. How can I go over all PlantParts in the RowMapper.

I would like the RowMapper to do something like this after setting id and plantname:

//For the first line
if(rs.getString("leaves") != null){
    plant.add(new PlantRow(rs.getString("leaves"),
            rs.getInt("pedicle"), rs.getInt("petals")));
}
while (rs.next()){
    if(rs.getString("leaves") != null){
        plant.add(new PlantRow(rs.getString("leaves"),
                rs.getInt("pedicle"), rs.getInt("petals")));
    }
}

I do not mind if there is another way to do it, without using RowMapper, I just need something that would make it work.