package houserenter.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import houserenter.entity.House;
@Service
public class HouseService {
@Autowired
private JdbcTemplate jdbcTemplate;
@PostConstruct
public void generateMockHouses() {
jdbcTemplate.execute("drop table if exists house");
jdbcTemplate.execute("create table house(id varchar(20) primary key, name varchar(100), detail varchar(500))");
jdbcTemplate.update("insert into house values(?, ?, ?)", "1", "金科嘉苑3-2-1201", "详细信息");
jdbcTemplate.update("insert into house values(?, ?, ?)", "2", "万科橙9-1-501", "详细信息");
}
public List findHousesInterested(String userName) {
// 这里查找该用户感兴趣的房源,省略,改为用模拟数据
return jdbcTemplate.query(
"select id,name,detail from house",
new HouseMapper());
}
public House findHouseById(String houseId) {
return jdbcTemplate.queryForObject(
"select id,name,detail from house where id = ?",
new Object[]{houseId},
new HouseMapper());
}
public void updateHouseById(House house) {
jdbcTemplate.update(
"update house set id=?, name=?, detail=? where id=?",
house.getId(), house.getName(), house.getDetail(), house.getId());
}
private static final class HouseMapper implements RowMapper {
@Override
public House mapRow(ResultSet rs, int rowNum) throws SQLException {
return new House(rs.getString("id"), rs.getString("name"), rs.getString("detail"));
}
}
}
Java代码 - 实体类
package houserenter.entity;
public class House {
private String id;
private String name;
private String detail;
public House(String id, String name, String detail) {
super();
this.id = id;
this.name = name;
this.detail = detail;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "House [id=" + id + ", name=" + name + ", detail=" + detail + "]";
}
}