Database Connectivity - DAO Flashcards
JDBC
Java Database Connectivity
Java Database Connectivity
a library that allows Java applications to access SQL databases in a standard way.
Spring JDBC
a framework that provides an abstraction for JDBC making it easier to use,
provides a consistent way to create queries, handle results, deal with exception, and automatically provides transactions
Connection Pool
makes multiple connections to the database and keeps them open. When an application needs a connection it “checks one out” from the pool. When it is finished with it, it returns it to be reused
Connection String
like an address (URL) to a web site only used to connect to a database.It includes details on what vendor driver to use, where the database is located on a network, the name of the database to connect to, and the credentials (user id / password)
Making a Connection
BasicDataSource dvdstoreDataSource = new BasicDataSource();
dvdstoreDataSource.setUrl(“jdbc:postgresql://localhost:5432/dvdstore”);
dvdstoreDataSource.setUsername(“postgres”);
dvdstoreDataSource.setPassword(“postgres1”);
BasicDataSource
The org.apache.commons.dbcp2.BasicDataSource provides the ability to make a database connection and a Connection Pool.
The setUrl takes a connection string as an argument:
jdbc:postgresql://localhost:5432/dvdstore
jdbc:postgresql:// tells the DataSource to use JDBC with the PostgreSQL Vendor Driver
localhost:5432 tells the DataSource the location of the database on a network, in this case the same computer.
dvdstore is the name of the database which to connect
setUsername() and setPassword()
methods set the username and password to use when connecting to the database
JDBCTemplate allows for the execution of queries using the DataSource.
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
Queries that return results, like SELECT, use
jdbcTemplate.queryForRowSet(sql, params1…paramsN)
Queries that do not return results, like INSERT, UPDATE, and DELETE, use
jdbcTemplate.update(sql, params1…paramsN)
Parameters
values used in a query should not be concatenated, unless the source of the value is a known as safe.
DAO Pattern
Data Access Object (DAO)
Data Access Object (DAO)
design pattern encapsulates the details of persistent storage inside of classes whose only role is to store and retrieve data