Tuesday, January 25, 2022

How to configure Spring Boot Jdbc template





Let's begin, open dilsecodie GOTO: 
Step1: First do add Maven Spring JdbcTemplate dependency in the pom.xml file. 

Step2: Then check the example given by dilsecodie

Step3: JDBC template used same as JDBC, you can write the custom query, use other methods also like map, list, object[], get the class object in list etc.

Step4: You can use in any service by doing @Autowired JdbcTemplate JDBC;


you can use to make a complete CRUD flow, write SQL sentences, some wrappers, and you get it, a complete and functional persistence layer.

Lets see some explaintion for JDBC with spring boot .

 either through an xml file,database fetching and storing is then further abstracted away behind an interface called a Repository .
first need to package in your Impl class 
import org.springframework.jdbc.core.JdbcTemplate;
this package bascially provide you JDBC class object which you need to autowire in your class
@Autowired
JdbcTemplate jdbc; - this reference variable used in object.
for select example 
public List<Map<String, Object>> getselectdata1() {
String sql = "SELECT DISTINCT l1id , name FROM Dilsecodie ";
List<Map<String, Object>> rows = jdbc.queryForList(sql);
return rows;
}
It will provide you data as shown in query and output stored in list form 

Important point to be note database connection will be same as in datasource 

Lets see how to insert data using jdbc templete 
public Boolean insertFromUser(UserQueryForsetVal uq) {
jdbc.update("INSERT INTO userDilsecodiequery(userid, userloginid,t1,t2,t3,
                 queryasked,queryurl,ExpertList) VALUES(?,?,?,?,?,?,?,?)", uq.getUserid(),
uq.getUserloginid(), uq.gett1(), uq.gett2(),
                      uq.gett3(), uq.getQueryasked(),uq.getQueryurl(),uq.getExpertList());
return true;
}
this above example give you an idea about insert query can insert your data can you this example 
and modify as per your requirement .

Now if required to update your recored then  lets understand by exmaple 
public void updateUserQueryStatus(Integer refId, Integer status) {
String sql = "UPDATE userDilsecodiequery SET status = " + status +
                 " WHERE refid = " + refId;
jdbc.execute(sql);
}

For integer - class query example
public int getalluser() {
int username =1 ;
String sql = "SELECT COUNT(expert_email) as count FROM alluserdilsecodie WHERE is_approved=1  ";

int count = this.jdbc.queryForObject(sql, Integer.class);
System.out.println("get count of "+count);
return count ;
} -  above example can be used in retutn integer value in Impl logic , and also used in number values stored in integer object.
So basically jdbc provide you to make query according to your need , we also write any type of join in query
as can check in example jdbc.execute your query 
JDBC can handle your connections by it self .




Note*: Still having Problem, can ask in doubt section.

No comments:

Post a Comment