Spring : JdbcTemplate Example

JdbcTemplate Example

Create Following files in java project in eclipse.




Database name: test
Table : employee (id, name, salary)
You need spring jar files and MySql Driver file.

1. Employee.java

              Property: id, name, salary
              Create constructor, getters and setters.

2. EmployeeDao.java

        public class EmployeeDao {
private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public int saveEmployee(Employee e) {
String query = "insert into employee values('" + e.getId() + "','"
+ e.getName() + "','" + e.getSalary() + "')";
return jdbcTemplate.update(query);
}

public int updateEmployee(Employee e) {
String query = "update employee set name='" + e.getName()
+ "',salary='" + e.getSalary() + "' where id='" + e.getId()
+ "' ";
return jdbcTemplate.update(query);
}

public int deleteEmployee(Employee e) {
String query = "delete from employee where id='" + e.getId() + "' ";
return jdbcTemplate.update(query);
}
}


3. TestMain.java

       public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"myBean.xml");

EmployeeDao dao = (EmployeeDao) ctx.getBean("edao");
/*
int status = dao.saveEmployee(new Employee(102, "Amit", 35000));
System.out.println(status);
*/

/*
int status=dao.updateEmployee(new Employee(102,"Piyush",15000));
System.out.println(status);
*/

Employee e=new Employee();
e.setId(102);
int status=dao.deleteEmployee(e);
System.out.println(status);
}

4. myBean.xml

     Create 3 beans ds, jdbcTemplate and edao.

         <bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>

<bean id="edao" class="com.smgc.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
   

Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes