DataSource vs DriverManager
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every DAO that calls DriverManager.getConnection knows the database URL and password. Switching to a faster way of getting connections would mean editing every one of those classes.
The javax.sql.DataSource interface
A DataSource is the standard JDK interface (javax.sql) for an object that hands out database connections. You configure it once with the URL, user and password, then call getConnection() wherever a connection is needed.
DriverManager.getConnection(url, user, password) is a static method, so every caller must know the URL and the password. A DataSource is an object behind an interface, so callers only ask it for a connection.
// The part of javax.sql.DataSource you use every day (simplified view)public interface DataSource { Connection getConnection() throws SQLException; Connection getConnection(String username, String password) throws SQLException;}
// Usage: configured once somewhere, then only thistry (Connection con = dataSource.getConnection()) { // run SQL}That one difference makes pooling, testing and frameworks possible, because you can swap the object for a faster one. JDBC documentation calls DataSource the preferred way to get connections; DriverManager still works and is fine for a quick test program.
CommonDataSource and Wrapper. You rarely call them.MysqlDataSource: a simple, non-pooled DataSource
MysqlDataSource is the MySQL driver's own DataSource, in package com.mysql.cj.jdbc. You give it the URL, user and password with setters, and every getConnection() opens a brand-new connection.
Example 1 sets up a MysqlDataSource once and borrows three connections from it. Example 2 shows the mistake of forgetting setUser.
Example 1 · MysqlDataSource: a new server connection on every call
Runs in: a Maven project with the MySQL driver and the ShopLite database
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javax.sql.DataSource;
public class MysqlDataSourceDemo { static long connectionId(Connection con) throws SQLException { try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT CONNECTION_ID()")) { rs.next(); return rs.getLong(1); } }
public static void main(String[] args) throws SQLException { MysqlDataSource mysql = new MysqlDataSource(); mysql.setURL(System.getenv("DB_URL")); mysql.setUser(System.getenv("DB_USER")); mysql.setPassword(System.getenv("DB_PASSWORD"));
DataSource dataSource = mysql; // from here on, only the interface is used
for (int i = 1; i <= 3; i++) { try (Connection con = dataSource.getConnection()) { System.out.println("Borrow " + i + ": server connection id " + connectionId(con) + " (" + con.getClass().getSimpleName() + ")"); } } }}Borrow 1: server connection id 7754 (ConnectionImpl) Borrow 2: server connection id 7760 (ConnectionImpl) Borrow 3: server connection id 7761 (ConnectionImpl)
What this code does
- The settings go into the
MysqlDataSourceobject once. After that, the loop uses only theDataSourceinterface and callsgetConnection()with no arguments. SELECT CONNECTION_ID()returns the id MySQL gave this session. It is different every time, and the class is the driver's ownConnectionImpl:MysqlDataSourceopens a brand-new connection per call, just likeDriverManager.- Your ids will differ: MySQL numbers every connection it ever accepts.
Example 2 · Mistake: forgetting setUser
Runs in: a Maven project with the MySQL driver and the ShopLite database
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;import java.sql.SQLException;
public class MissingUserDemo { public static void main(String[] args) { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setURL(System.getenv("DB_URL")); dataSource.setPassword(System.getenv("DB_PASSWORD")); // setUser(...) forgotten
try (Connection con = dataSource.getConnection()) { System.out.println("Connected"); } catch (SQLException e) { System.out.println("SQL state " + e.getSQLState() + ", error " + e.getErrorCode()); System.out.println(e.getMessage()); } }}SQL state 28000, error 1045 Access denied for user 'asha'@'localhost' (using password: YES)
What this code does
- With no
setUser(...), Connector/J falls back to the name you are logged in to your computer with (hereasha). MySQL has no such user, so the login fails. - Error 1045 with SQL state 28000 always means the login failed. Read the user name in the message first: it tells you which value the driver really sent.
So MysqlDataSource is not faster than DriverManager. Its value is the shape: an object you set up once and pass around as a plain DataSource. Instead of a URL you can also call setServerName, setPortNumber and setDatabaseName.
Your code now imports a driver class, so the compiler needs the driver. If mysql-connector-j has <scope>runtime</scope> in pom.xml, the build fails with package com.mysql.cj.jdbc does not exist. Remove the scope line (compile is the default) while you use MysqlDataSource.
Fix the error
Fix the missing user name
Read the real error, then pick the line that fixes it.
The environment variable is DB_USER, but the program cannot log in.
Error
java.sql.SQLException: Access denied for user 'asha'@'localhost' (using password: YES) SQL state 28000, error 1045
Code that depends on DataSource doesn't care whether it is pooled
Programming to the interface means declaring fields and parameters with the interface type, here DataSource, never MysqlDataSource or a pool class. The object passed in decides how connections are made.
Example 3 is a StockReport that accepts any DataSource. Only main names the concrete class.
Example 3 · A class that needs only "some DataSource"
Runs in: a Maven project with the MySQL driver and the ShopLite database
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.sql.DataSource;
class StockReport { private final DataSource dataSource;
StockReport(DataSource dataSource) { this.dataSource = dataSource; }
void printLowStock(int limit) throws SQLException { String sql = "SELECT sku, name, stock FROM products " + "WHERE is_active = TRUE AND stock <= ? ORDER BY stock, sku"; try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setInt(1, limit); try (ResultSet rs = ps.executeQuery()) { System.out.println("Active products with stock <= " + limit + ":"); while (rs.next()) { System.out.printf(" %-10s %-28s %3d%n", rs.getString("sku"), rs.getString("name"), rs.getInt("stock")); } } } }}
public class StockReportDemo { public static void main(String[] args) throws SQLException { MysqlDataSource mysql = new MysqlDataSource(); mysql.setURL(System.getenv("DB_URL")); mysql.setUser(System.getenv("DB_USER")); mysql.setPassword(System.getenv("DB_PASSWORD"));
StockReport report = new StockReport(mysql); // any DataSource fits here report.printLowStock(15); }}Active products with stock <= 15: ACC-M331 Logitech M331 Silent Mouse 0 LAP-HPV15 HP Victus 15 Gaming 5 MOB-IP15 iPhone 15 128GB 8 LAP-IPS3 Lenovo IdeaPad Slim 3 12 HK-COOK3L Prestige Pressure Cooker 3L 15
What this code does
StockReportimports onlyjavax.sql.DataSource. It has no idea which driver, URL or pool is behind it, and it never needs a password.- Only
mainnames the concrete classMysqlDataSource. Passing a pooledDataSourcethere instead changes nothing insideStockReport.
The benefit shows up three times in this course. The next lesson swaps MysqlDataSource for a connection pool by changing one line in main. Tests can pass a DataSource for a test database. Spring Boot creates the DataSource for you and passes it to your classes.
A class that takes a DataSource must still open and close a connection per piece of work. Keeping one Connection in a field defeats the purpose, as a practice exercise shows.
Predict the output
Predict the switch to a pool
main now passes a pooled DataSource instead of a MysqlDataSource. How much of StockReport changes?
Replacing the ConnectionFactory with a DataSource in DAOs
Wiring is the one place, usually main, that creates the objects of an application and hands them to each other. It is the only code that names the concrete DataSource class.
The ConnectionFactory from the DAO module was a hand-made DataSource: an object with a method that returns connections. Replace it with the JDK interface.
// ShopLite: the only class that opens connectionspublic class JdbcTransactionManager implements TransactionManager { private final DataSource dataSource; // was: ConnectionFactory connections private final ThreadLocal<Connection> current = new ThreadLocal<>();
public JdbcTransactionManager(DataSource dataSource) { this.dataSource = dataSource; }
// lease() and inTransaction() now call dataSource.getConnection(); // nothing else in the class changes, and no DAO changes at all}In ShopLite only one class opens connections: JdbcTransactionManager. Every DAO borrows through its lease() method, so the refactor touches that class and Main, and none of the four DAOs. That is the payoff of the layers built in the DAO module.
Example 4 · A DAO that takes a DataSource in its constructor
Runs in: a Maven project with the MySQL driver and the ShopLite database
import com.mysql.cj.jdbc.MysqlDataSource;
import java.math.BigDecimal;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Optional;import javax.sql.DataSource;
record Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) {}
class DataAccessException extends RuntimeException { DataAccessException(String message, Throwable cause) { super(message, cause); }}
interface ProductDao { Optional<Product> findById(int id);}
class JdbcProductDao implements ProductDao { private static final String FIND_BY_ID = "SELECT product_id, sku, name, category_id, price, stock, is_active FROM products WHERE product_id = ?";
private final DataSource dataSource; // was: private final ConnectionFactory connections;
JdbcProductDao(DataSource dataSource) { this.dataSource = dataSource; }
@Override public Optional<Product> findById(int id) { try (Connection con = dataSource.getConnection(); // was: connections.getConnection() PreparedStatement ps = con.prepareStatement(FIND_BY_ID)) { ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { return rs.next() ? Optional.of(mapRow(rs)) : Optional.empty(); } } catch (SQLException e) { throw new DataAccessException("Could not load product " + id, e); } }
private static Product mapRow(ResultSet rs) throws SQLException { return new Product(rs.getInt("product_id"), rs.getString("sku"), rs.getString("name"), rs.getInt("category_id"), rs.getBigDecimal("price"), rs.getInt("stock"), rs.getBoolean("is_active")); }}
public class DataSourceDaoDemo { public static void main(String[] args) { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setURL(System.getenv("DB_URL")); dataSource.setUser(System.getenv("DB_USER")); dataSource.setPassword(System.getenv("DB_PASSWORD"));
ProductDao products = new JdbcProductDao(dataSource); System.out.println(products.findById(4).map(Product::name).orElse("not found")); System.out.println(products.findById(99).map(Product::name).orElse("not found")); products.findById(1).ifPresent(p -> System.out.println(p.sku() + " costs Rs " + p.price())); }}Lenovo IdeaPad Slim 3 not found MOB-RN13 costs Rs 17999.00
What this code does
- The two
// was:comments show the whole change from the DAO module: the field type and the call that gets a connection. The SQL, the row mapping and the error translation stay the same. - The connection is still opened and closed inside one method with try-with-resources, so the DAO is correct for a non-pooled and a pooled
DataSourcealike. - In the ShopLite project each type lives in its own file; here they share one file so the example runs on its own.
Example 5 · src/main/java/com/shoplite/app/Main.java (wiring a DataSource)
Runs in: the shoplite-console Maven project
package com.shoplite.app;
import com.mysql.cj.jdbc.MysqlDataSource;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcCategoryDao;import com.shoplite.dao.JdbcCustomerDao;import com.shoplite.dao.JdbcOrderDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.service.CustomerService;import com.shoplite.service.OrderService;import com.shoplite.service.ProductService;
import java.util.Scanner;import javax.sql.DataSource;
/** The one place where every object is created and connected. */public class Main {
public static void main(String[] args) { DataSource dataSource = createDataSource(DatabaseConfig.load()); JdbcTransactionManager tx = new JdbcTransactionManager(dataSource); // was: a ConnectionFactory
JdbcProductDao productDao = new JdbcProductDao(tx); JdbcCategoryDao categoryDao = new JdbcCategoryDao(tx); JdbcCustomerDao customerDao = new JdbcCustomerDao(tx); JdbcOrderDao orderDao = new JdbcOrderDao(tx);
ProductService productService = new ProductService(productDao, categoryDao); CustomerService customerService = new CustomerService(customerDao); OrderService orderService = new OrderService(tx, customerDao, productDao, orderDao);
new ConsoleMenu(new Scanner(System.in), productService, customerService, orderService).run(); }
/** The only line that knows which DataSource class is used. */ private static DataSource createDataSource(DatabaseConfig config) { MysqlDataSource mysql = new MysqlDataSource(); mysql.setURL(config.url()); mysql.setUser(config.user()); mysql.setPassword(config.password()); return mysql; }}=== ShopLite === 1. Browse products 2. Register customer 3. Place order 4. Order history 0. Exit Choose: 1 Page 1 of 3 (14 products) #11 BK-ATOMIC Atomic Habits Rs 399.00 stock 50 #6 ACC-AD141 boAt Airdopes 141 Rs 1299.00 stock 120 #9 BK-CLEAN Clean Code Rs 499.00 stock 30 #12 FSH-KURTA Cotton Kurta Rs 899.00 stock 35 #5 LAP-HPV15 HP Victus 15 Gaming Rs 64990.00 stock 5 [n]ext, [p]revious, [q]uit: q === ShopLite === 1. Browse products 2. Register customer 3. Place order 4. Order history 0. Exit Choose: 0 Bye
What this code does
createDataSourceis the only place that knows aboutMysqlDataSource. Everything after it receives aDataSource(throughJdbcTransactionManager), so the four DAOs and three services did not change at all.- The menu works exactly as before.
ConnectionFactoryis no longer used anywhere, so you can delete it;DatabaseConfigstays until the configuration lesson replaces it. - The run above is
mvn -q compile exec:javawithDB_URL,DB_USERandDB_PASSWORDset, typing 1, q and 0.
Order of execution
Order the refactor
Tap the steps of replacing ConnectionFactory with a DataSource, in order.
Why frameworks such as Spring always hand you a DataSource
Frameworks build one DataSource at startup from your settings and pass it to every class that needs the database. Spring Boot, which this course uses from Section 15, reads spring.datasource.url, username and password and creates a HikariCP pool behind the DataSource interface.
// Section 15 preview: Spring Boot creates the DataSource and calls this constructor@Repositoryclass JdbcProductDao implements ProductDao { private final DataSource dataSource;
JdbcProductDao(DataSource dataSource) { // the same shape you wrote in this lesson this.dataSource = dataSource; }}Your classes ask for a DataSource in their constructor and never call DriverManager. Application servers such as Tomcat work the same way: the server owns the pool and your code looks it up as a DataSource.
So the habit from this lesson carries straight into real projects: one place creates the DataSource, and everything else receives it.
Next step
Check your understanding
12 quick questions