JDBCTemplate set nested POJO with BeanPropertyRowMapper

后端 未结 5 2066
慢半拍i
慢半拍i 2020-12-07 22:17

Given the following example POJO\'s: (Assume Getters and Setters for all properties)

class User {
    String user_name;
    String display_name;
}

class Mes         


        
5条回答
  •  無奈伤痛
    2020-12-07 22:44

    A bit late to the party however I found this when I was googling the same question and I found a different solution that may be favorable for others in the future.

    Unfortunately there is not a native way to achieve the nested scenario without making a customer RowMapper. However I will share an easier way to make said custom RowMapper than some of the other solutions here.

    Given your scenario you can do the following:

    class User {
        String user_name;
        String display_name;
    }
    
    class Message {
        String title;
        String question;
        User user;
    }
    
    public class MessageRowMapper implements RowMapper {
    
        @Override
        public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = (new BeanPropertyRowMapper<>(User.class)).mapRow(rs,rowNum);
            Message message = (new BeanPropertyRowMapper<>(Message.class)).mapRow(rs,rowNum);
            message.setUser(user);
            return message;
         }
    }
    

    The key thing to remember with BeanPropertyRowMapper is that you have to follow the naming of your columns and the properties of your class members to the letter with the following exceptions (see Spring Documentation):

    • column names are aliased exactly
    • column names with underscores will be converted into "camel" case (ie. MY_COLUMN_WITH_UNDERSCORES == myColumnWithUnderscores)

提交回复
热议问题