Как многим кто хоть когда нибудь работал со Spring фреймворком — не смотря на тонны оберток он существенно ускоряет процесс разработки и в случае DAO слоя так же не является исключением.
Data Access Object (DAO) — широко распространенный паттерн для сохранения объектов бизнес-области в базе данных. В самом широком смысле, DAO — это класс, содержащий CRUD методы для конкретной сущности.
содержание
Пример без Spring JdbcTemplate
Без JdbcTemplate, нам приходится писать много лишнего кода (создавать соединение, закрывать соединение, отлавливать исключения) причем делать это приходится в каждом DAO методе – insert, update и delete. Это не эффективно, громоздко и утомительно.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(Subscriber subscriber){ String sql = "INSERT INTO SUBSCRIBERS(IP, EMAIL, AGE) VALUES (?, ?, ?)"; Connection conn = null; try { //каждый раз открываем соединение conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, subscriber.getIp()); ps.setString(2, subscriber.getEmail()); ps.setInt(3, subscriber.getAge()); ps.executeUpdate(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } finally { //каждый раз закрываем соединение if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } |
Пример с Spring JdbcTemplate
С JdbcTemplate, вы экономите время на разработку, потому что JdbcTemplate выполняет половину работы за Вас.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Autowired private DataSource dataSource; @Autowired private JdbcTemplate jdbcTemplate; public void insert(Subscriber subscriber){ String sql = "INSERT INTO SUBSCRIBERS(IP, EMAIL, AGE) VALUES (?, ?, ?)"; jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new Object[] { subscriber.getCustId(), subscriber.getName(), subscriber.getAge() }); } |
Пример с Spring JdbcDaoSupport
При наследовании от JdbcDaoSupport, инициализировать JdbcTemplate нам больше не нужно. Достаточно заинжектить его и мы сможем получать его каждый раз с помощью метода getJdbcTemplate ().
1 2 3 4 5 6 7 8 9 |
public class JdbcCustomerDAO extends JdbcDaoSupport implements CustomerDAO { //no need to set datasource here public void insert(Customer customer){ String sql = "INSERT INTO SUBSCRIBERS(IP, EMAIL, AGE) VALUES (?, ?, ?)"; getJdbcTemplate().update(sql, new Object[] { customer.getCustId(), customer.getName(),customer.getAge() }); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/leodev" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> </beans> |
1 2 3 4 5 6 7 8 9 10 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerDAO" class="ru.leodev.subscriber.dao.impl.JdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> </beans> |
или используя Java Bean Configuration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName")); dataSource.setUrl(env.getRequiredProperty("jdbc.url")); dataSource.setUsername(env.getRequiredProperty("jdbc.username")); dataSource.setPassword(env.getRequiredProperty("jdbc.password")); return dataSource; } @Bean public JdbcTemplate getjdbcTemplate() throws NamingException { return new JdbcTemplate(dataSource()); } |
Maven зависимости:
1 2 3 4 5 |
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.5.RELEASE</version> </dependency> |