我的任务是将基于Map
的存储升级到基于数据库的存储。我的项目配置基于注释。你能解释一下我应该采取哪些措施来实现这个目标吗?以及如何更改我的dao
图层代码:
public class TicketDao {
Set<Ticket> tickets = new HashSet<>();
public Set<Ticket> getAll() {
return tickets;
}
public void remove(Ticket ticket){
tickets.remove(ticket);
}
public void put(Ticket ticket){
tickets.add(ticket);
}
}
答案 0 :(得分:2)
配置DataSource
和JdbcTemplate
。最简单的配置:
@Configuration
public class JdbcConfig {
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("");
dataSource.setUrl("");
dataSource.setUsername("");
dataSource.setPassword("");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
将JdbcTemplate
注入dao并使用它
public class TicketDao {
public static final String DELETE_QUERY = "delete from Ticket where id = ?";
public static final String INSERT_QUERY = "insert into Ticket values(?, ?)";
public static final String GET_ALL_QUERY = "select * from Tickets";
@Autowired
JdbcTemplate jdbcTemplate;
public Set<Ticket> getAll() {
return new HashSet<>(jdbcTemplate.query(GET_ALL_QUERY, new RowMapper<Ticket>() {
@Override
public Ticket mapRow(ResultSet rs, int rowNum) throws SQLException {
Ticket ticket = new Ticket();
ticket.setId(rs.getString(1));
//other fields mapping
return ticket;
}
}));
}
public void remove(Ticket ticket){
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(DELETE_QUERY);
statement.setString(1, ticket.getId());
return statement;
}
});
}
public void put(Ticket ticket){
Object[] values = {ticket.getId(), ticket.getName()};
int[] types = {Types.VARCHAR, Types.VARCHAR};
jdbcTemplate.update(INSERT_QUERY, values, types);
}
}