Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java One More Time With Feeling

Christopher David
PLUS
Christopher David
Courses Plus Student 20,027 Points

Understanding of ColumnMapping

I don't understand why column mapping is needed in the findByCourseId function and not the add function. Can someone explain this to me?

    @Override
    public void add(Review review) throws DaoException {
        String sql = "INSERT INTO reviews(course_id, rating, comment) VALUES (:courseId, :rating, :comment)";
        try (Connection con = sql2o.open()) {
            int id = (int) con.createQuery(sql)
                    .bind(review)
                    .executeUpdate()
                    .getKey();
            review.setId(id);
        } catch (Sql2oException ex) {
            throw new DaoException(ex, "Problem adding course");
        }
    }

    @Override
    public List<Review> findByCourseId(int courseId) {
        try (Connection con = sql2o.open()) {
            return con.createQuery("SELECT * from reviews WHERE course_id = :courseId")
                    .addColumnMapping("COURSE_ID", "courseId")
                    .addParameter("courseId", courseId)
                    .executeAndFetch(Review.class);
        }
    }

1 Answer

Jeremiah Shore
Jeremiah Shore
31,168 Points

I haven't researched it in depth, but I think it has to do with the Review model class and the way the field is named, specifically courseId. I'm assuming that when Sql2o is retrieving and mapping, it's a slightly different process as far as it inferring which method to use.

In other words, it sees a course_id column and doesn't know where to map that because there is no field that follows the same naming convention. I'm not sure why it works in persisting but not in retrieving; kinda stumped on that. Maybe that's something we could contribute to the Sql2o project.

I can tell you this though... in my project I simply refactored courseId in Review to course_id and followed that new naming convention uniformly in my ReviewDao implementation. By doing this, I didn't have to add the column mapping like you did. I am thankful, however, that you posted that here so I know it's availalble when using this ORM :)