package com.lazyrodi.crud;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class UserDao {
JdbcTemplate mTemplate;
public void setTemplate(JdbcTemplate template) {
System.out.println("[UserDao] Created");
mTemplate = template;
}
public int save(User user) {
System.out.println("[UserDao] save(), email = " + user.getEmail());
String sql = "insert into User(email, password, number, age)"
+ "values('" + user.getEmail() + "','" + user.getPassword() + "','" + user.getNumber() + "', " + user.getAge() + ")";
return mTemplate.update(sql);
}
public int update(User user) {
System.out.println("[UserDao] update(), email = " + user.getEmail());
String sql = "update User set password='" + user.getPassword()
+ "', number='" + user.getNumber()
+ "', age=" + user.getAge()
+ " where email='" + user.getEmail() + "'";
return mTemplate.update(sql);
}
public int delete(String email) {
System.out.println("[UserDao] delete(), email = " + email);
String sql = "delete from User where email='" + email + "'";
return mTemplate.update(sql);
}
public User getUserByEmail(String email) {
System.out.println("[UserDao] getUserByEmail(), email = " + email);
String sql = "select * from User where email=?";
return mTemplate.queryForObject(sql, new Object[] {email}, new BeanPropertyRowMapper<User>(User.class));
}
public List<User> getUsers() {
System.out.println("[UserDao] getUsers()");
return mTemplate.query("select * from User", new RowMapper<User>() {
public User mapRow(ResultSet rs, int row) throws SQLException {
User user = new User();
user.setEmail(rs.getString(1));
user.setPassword(rs.getString(2));
user.setNumber(rs.getString(3));
user.setAge(rs.getInt(4));
return user;
}
});
}
}