Insert Data using Object and Delete row using Id

 Step 1:

public class Course {

private long id;

private String name;

private String author;

public Course() {

super();

}

public Course(long id, String name, String author) {

super();

this.id = id;

this.name = name;

this.author = author;

}

public long getId() {

return id;

}

public String getName() {

return name;

}

public String getAuthor() {

return author;

}

@Override

public String toString() {

return "Course [id=" + id + ", name=" + name + ", author=" + author + "]";

}


}


Step 2:

public class CourseJdbcRepository {


@Autowired

private JdbcTemplate springjdbcTemplate;

//""" will be known as text block

//(this allows us to retain the formatting for your queries which allow to easy to understand)

private static String INSERT_QUERY_WITH_PARAM=

"""

insert into course (id,name,author)

values(?,?,?)

""";

public void insertFromObject(Course course) {

springjdbcTemplate.update(INSERT_QUERY_WITH_PARAM, course.getId(), course.getName(), course.getAuthor());

}

}


Step 3

@Component

public class CourseJdbcCommandLineRunner implements CommandLineRunner {

@Autowired

CourseJdbcRepository courseJdbcRepository;


@Override

public void run(String... args) throws Exception {

courseJdbcRepository.insertFromObject(new Course(2, "Learn Spring Boot", "Irfan Khan"));

}


}


DELETE Row using ID


@Component

public class CourseJdbcCommandLineRunner implements CommandLineRunner {

@Autowired

CourseJdbcRepository courseJdbcRepository;


@Override

public void run(String... args) throws Exception {

courseJdbcRepository.insert();

courseJdbcRepository.insertFromObject(new Course(2, "Learn Spring Boot", "Irfan Khan"));

courseJdbcRepository.insertFromObject(new Course(3, "Learn Hibernate Boot", "Irfan Khan"));

courseJdbcRepository.deleteById(1);

}


}


index 1 value got deleted



@Repository

public class CourseJdbcRepository {


@Autowired

private JdbcTemplate springjdbcTemplate;

//""" will be known as text block

//(this allows us to retain the formatting for your queries which allow to easy to understand)

private static String INSERT_QUERY=

"""

insert into course (id,name,author)

values(1,'Learn Java', 'khanDev')

""";

private static String INSERT_QUERY_WITH_PARAM=

"""

insert into course (id,name,author)

values(?,?,?)

""";

private static String DELETE_QUERY =

"""

delete from course where id = ?

""";


public void insert() {

springjdbcTemplate.update(INSERT_QUERY);

}

public void insertFromObject(Course course) {

springjdbcTemplate.update(INSERT_QUERY_WITH_PARAM, course.getId(), course.getName(), course.getAuthor());

}

public void deleteById(long id) {

springjdbcTemplate.update(DELETE_QUERY,id);

}

}


Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API