public class Course {
private long id;
private String name;
private String author;
public Course() {}
public Course(long id, String name, String author) {
super();
this.id = id;
this.name = name;
this.author = author;
}
}
@Repository
public class CourseJdbcRepository {
@Autowired
private JdbcTemplate springJdbcTemplate;
private static String INSERT_QUERY = """ insert into course (id, name, author) values(?, ?,?); """;
private static String DELETE_QUERY = """ delete from course where id = ? """;
private static String SELECT_QUERY = """ select * from course where id = ? """;
public void insert(Course course) {
springJdbcTemplate.update(INSERT_QUERY, course.getId(), course.getName(), course.getAuthor());
}
public void deleteById(long id) {
springJdbcTemplate.update(DELETE_QUERY,id);
}
public Course findById(long id) {
return springJdbcTemplate.queryForObject(SELECT_QUERY, new BeanPropertyRowMapper<>(Course.class), id);
}
}
@Component
public class CourseCommandLineRunner implements CommandLineRunner{
@Autowired
private CourseJdbcRepository repository;
@Override
public void run(String... args) throws Exception {
repository.insert(new Course(1, "Learn AWS!", "Udemy"));
repository.insert(new Course(2, "Learn Azure!", "Udemy"));
repository.insert(new Course(3, "Learn GCP!", "Udemy"));
repository.deleteById(1);
System.out.println(repository.findById(2));
System.out.println(repository.findById(3));
}
}