Topic 6 – JDBC Abstraction and DAO

image 2

Play Store Application link – Spring Framework in 9 steps – Apps on Google Play

Github Project Link – (XML based) – https://github.com/kuldeep101990/SpringJDBC

Github Project Link – (Annotation based) – https://github.com/kuldeep101990/SpringJDBCAnnotation

To make it easier for developers to work with databases, Spring provides an abstraction layer on top of JDBC called the JDBC Template. This abstraction layer provides a simplified interface that encapsulates the low-level details of working with JDBC. With the JDBC Template, developers can focus on writing SQL queries and working with the data returned, without worrying about the underlying implementation details.

DAO (Data Access Object) is a design pattern that separates the business logic of an application from the details of accessing data from a database. In essence, a DAO provides a way for developers to encapsulate the CRUD (Create, Read, Update, Delete) operations for a particular data entity (e.g. a Customer or Order) in a single place.

First, here’s an example without Spring’s JDBC abstraction layer or DAO pattern:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CustomerDAOWithoutSpring {
    
    private final String url = "jdbc:mysql://localhost:3306/mydb";
    private final String user = "root";
    private final String password = "password";
    
    public void createCustomer(Customer customer) throws SQLException {
        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String sql = "INSERT INTO customers (name, email) VALUES (?, ?)";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, customer.getName());
                stmt.setString(2, customer.getEmail());
                stmt.executeUpdate();
            }
        }
    }
    
    public Customer getCustomerById(int id) throws SQLException {
        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String sql = "SELECT * FROM customers WHERE id = ?";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setInt(1, id);
                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        String name = rs.getString("name");
                        String email = rs.getString("email");
                        return new Customer(id, name, email);
                    } else {
                        return null;
                    }
                }
            }
        }
    }
    
}

This code defines a CustomerDAOWithoutSpring class that uses raw JDBC to perform basic CRUD operations on a MySQL database. Note that the code is verbose and requires developers to manually handle database connections, prepared statements, and result sets.

Now, here’s an example that uses Spring’s JDBC abstraction layer and DAO pattern:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.List;
@Repository
public class CustomerDAOWithSpring {
    private final JdbcTemplate jdbcTemplate;
    @Autowired
    public CustomerDAOWithSpring(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    private final String url = "jdbc:mysql://localhost:3306/mydb";
    private final String user = "root";
    private final String password = "password";
    private final DataSource dataSource = createDataSource();
    private DataSource createDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }
    public void createCustomer(Customer customer) {
        String sql = "INSERT INTO customers (name, email) VALUES (?, ?)";
        jdbcTemplate.update(sql, customer.getName(), customer.getEmail());
    }
    public Customer getCustomerById(int id) {
        String sql = "SELECT * FROM customers WHERE id = ?";
        RowMapper<Customer> rowMapper = (rs, rowNum) ->
                new Customer(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, rowMapper);
    }
    public List<Customer> getAllCustomers() {
        String sql = "SELECT * FROM customers";
        RowMapper<Customer> rowMapper = (rs, rowNum) ->
                new Customer(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
        return jdbcTemplate.query(sql, rowMapper);
    }
    public void updateCustomer(Customer customer) {
        String sql = "UPDATE customers SET name = ?, email = ? WHERE id = ?";
        jdbcTemplate.update(sql, customer.getName(), customer.getEmail(), customer.getId());
    }
    public void deleteCustomer(int id) {
        String sql = "DELETE FROM customers WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }
}

This code defines a CustomerDAOWithSpring class that uses Spring’s JdbcTemplate to perform the same CRUD operations on the same MySQL database. Note that the code is much shorter and easier to read, and the JdbcTemplate takes care of the low-level details of managing database.

16 comments

  1. Thanks for revealing your ideas with this blog. Furthermore, a delusion regarding the lenders intentions when talking about foreclosed is that the standard bank will not take my payments. There is a certain quantity of time which the bank requires payments every now and then. If you are also deep within the hole, they should commonly desire that you pay the actual payment in whole. However, that doesn’t mean that they will not take any sort of installments at all. In the event you and the bank can be capable to work something out, this foreclosure approach may end. However, when you continue to miss out on payments under the new program, the foreclosed process can pick up where it was left off.

  2. Hello there, just became alert to your blog through Google, and found that it’s truly informative. I’m gonna watch out for brussels. I will appreciate if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  3. hello!,I like your writing so so much! percentage we keep up a correspondence extra approximately your article on AOL? I require a specialist in this area to solve my problem. Maybe that’s you! Taking a look ahead to peer you.

  4. Today, taking into consideration the fast lifestyle that everyone leads, credit cards get this amazing demand throughout the economy. Persons from every area are using the credit card and people who are not using the credit card have arranged to apply for 1. Thanks for revealing your ideas on credit cards.

  5. My brother recommended I might like this website. He used to be entirely right. This publish truly made my day. You cann’t believe simply how much time I had spent for this info! Thanks!

  6. We’re a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable information to work on. You’ve done an impressive job and our entire community will be thankful to you.

  7. I think that a foreclosure can have a significant effect on the borrower’s life. Foreclosures can have a Several to 10 years negative affect on a debtor’s credit report. A borrower who has applied for a mortgage or almost any loans for example, knows that your worse credit rating is usually, the more complicated it is to obtain a decent mortgage loan. In addition, it could possibly affect a borrower’s ability to find a reasonable place to lease or rent, if that gets the alternative real estate solution. Interesting blog post.

  8. My brother suggested I might like this website. He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this information! Thanks!

  9. Please let me know if you’re looking for a author for your blog. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Thank you!

  10. Helpful information. Fortunate me I found your website accidentally, and I am stunned why this coincidence didn’t happened in advance! I bookmarked it.

  11. Very great post. I simply stumbled upon your weblog and wished to say that I’ve really enjoyed surfing around your weblog posts. In any case I will be subscribing for your feed and I hope you write once more soon!

  12. Thanks for your fascinating article. Other thing is that mesothelioma cancer is generally a result of the breathing of material from mesothelioma, which is a extremely dangerous material. It’s commonly noticed among personnel in the building industry with long contact with asbestos. It’s also caused by living in asbestos protected buildings for years of time, Genetic makeup plays a crucial role, and some folks are more vulnerable for the risk in comparison with others.

  13. I抦 not sure where you are getting your information, but great topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this information for my mission.

  14. What I have usually told men and women is that when searching for a good online electronics retail store, there are a few factors that you have to factor in. First and foremost, you should really make sure to choose a reputable along with reliable store that has got great evaluations and classification from other customers and market sector advisors. This will make certain you are getting along with a well-known store that delivers good services and support to the patrons. Thanks for sharing your ideas on this blog site.

  15. Thanks for your post. My spouse and i have usually observed that a lot of people are needing to lose weight because they wish to appear slim as well as attractive. On the other hand, they do not always realize that there are more benefits for losing weight also. Doctors state that obese people come across a variety of health conditions that can be instantly attributed to their particular excess weight. The great thing is that people who are overweight and suffering from various diseases are able to reduce the severity of the illnesses simply by losing weight. You’ll be able to see a progressive but marked improvement with health when even a negligible amount of fat reduction is obtained.

  16. Hello! I know this is kind of off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *