info.gewton.slsecurity.dao.support.DefaultPostDao.java Source code

Java tutorial

Introduction

Here is the source code for info.gewton.slsecurity.dao.support.DefaultPostDao.java

Source

/*
 * Copyright 2011 Gewton Jhames <gewtonj@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package info.gewton.slsecurity.dao.support;

import info.gewton.slsecurity.model.Post;
import info.gewton.slsecurity.model.PostUser;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * Estratgia default para {@link PostDao}. Utiliza {@link JdbcTemplate}.
 * @author gewton
 */
public class DefaultPostDao extends JdbcDaoSupport implements PostDao {

    private static final String SQL_INSERT_POST = "insert into post(date_posted, text, username) values (?, ?, ?)";
    private static final String SQL_RETRIEVE_BY_USER = "select id, date_posted, text from post where username = ?";
    private static final String SQL_DELETE_POST = "delete from post where id = ?";

    @Override
    public void add(Post p) {
        getJdbcTemplate().update(SQL_INSERT_POST, p.getTimestamp(), p.getText(), p.getUser().getUsername());
    }

    @Override
    public List<Post> retrieveByUser(final PostUser u) {
        return getJdbcTemplate().query(SQL_RETRIEVE_BY_USER, new String[] { u.getUsername() },
                new ParameterizedRowMapper<Post>() {
                    public Post mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Post p = new Post();
                        p.setId(rs.getInt(1));
                        p.setTimestamp(rs.getDate(2));
                        p.setText(rs.getString(3));
                        p.setUser(u);
                        return p;
                    }
                });
    }

    @Override
    public void delete(Post p) {
        getJdbcTemplate().update(SQL_DELETE_POST, p.getId());
    }

}