Spring Boot 入門之持久層篇(三)
原文地址:Spring Boot 入門之持久層篇(三)
部落格地址:http://www.extlight.com 一、前言
上一篇《Spring Boot 入門之 Web 篇(二)》介紹了 Spring Boot 的 Web 開發相關的內容,項目的開發離不開資料,因此本篇開始介紹持久層相關的知識。 二、整合 JdbcTemplate 2.1 添加依賴
<!-- jdbc --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- mysql 驅動包 --><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency>
2.2 設定資料庫串連
在 application.properties 中添加:
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=tiger
其中,可以不指定 driver-class-name,因為 spring boot 會自動識別 url。 2.3 測試 2.3.1 建表
在 MySQL 中建立名為 springboot 的資料庫,在該庫中建立 user 表:
CREATE TABLE `user` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(50) NOT NULL, `password` VARCHAR(64) NOT NULL, `birthday` DATE NOT NULL, PRIMARY KEY (`id`))COLLATE='utf8_general_ci'ENGINE=InnoDBAUTO_INCREMENT=3;
2.3.2 建實體類
public class User implements Serializable{ private static final long serialVersionUID = -6249397911566315813L; private Integer id; private String username; private String password; private Date birthday;}
setter 和 getter 方法此處省略。 2.3.3 dao 介面
介面和實作類別如下:
public interface UserDao { public int insert(User user); public int deleteById(Integer id); public int update(User user); public User getById(Integer id);}@Repositorypublic class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int insert(User user) { String sql = "insert into user(id,username,password,birthday) values(?,?,?,?)"; return this.jdbcTemplate.update( sql, user.getId(), user.getUsername(), user.getPassword(), user.getBirthday() ); } @Override public int deleteById(Integer id) { String sql = "delete from user where id = ?"; return this.jdbcTemplate.update(sql,id); } @Override public int update(User user) { String sql = "update user set password = ? where id = ?"; return this.jdbcTemplate.update( sql, user.getPassword(), user.getId() ); } @Override public User getById(Integer id) { String sql = "select * from user where id = ?"; return this.jdbcTemplate.queryForObject(sql, new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setBirthday(rs.getDate("birthday")); return user; } },id); }}2.3.4 測試類別:
@RunWith(SpringRunner.class)@SpringBootTest