Spring JDBC 抽象框架 core 包提供了 JDBC 模板类,其中 JdbcTemplate 是 core 包的核 心类,所以其他模板类都是基于它封装完成的,JDBC 模板类是第一种工作模式。 JdbcTemplate 类通过模板设计模式帮助我们消除了冗长的代码,只做需要做的事情(即 可变部分),并且帮我们做了固定部分,如连接的创建及关闭。 Spring Boot 自动配置了 JdbcTemplate 数据模板。
JDBC 默认采用 org.apache.tomcat.jdbc.pool.DataSource 数据源,数据源的相关配置参考都封装在 org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration 类中。默认使 用 Tomcat 连接池,可以使用 spring.datasource.type 指定自定义的数据源类型。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jdbctemplate</groupId> <artifactId>jdbctemplate</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <!-- 声明项目配置依赖编码格式为 utf-8 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <fastjson.version>1.2.24</fastjson.version> </properties> <dependencies> <!--Spring Data Jpa依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>8.0.13</version><!--$NO-MVN-MAN-VER$--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
server.port =8089 server.servlet.context-path=/ spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?serverTimezone=UTC&autoReconnect=true spring.datasource.username=root spring.datasource.password=admin ##spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database=MySQL spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql=true
package com.tszr.jpa.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "t_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "username", unique = true, nullable = false, length = 64) private String username; @Column(name = "password", nullable = false, length = 64) private String password; @Column(name = "email", length = 64) private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.tszr.jpa.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.tszr.jpa.entity.User; public interface UserRepository extends JpaRepository<User, Integer> { /* 相当于select * from t_user where username = ? and password = ? */ public User findByUsernameAndPassword(String username, String password); @Query("select u from User u where u.username like %?1%") public List<User> getUserByUsername(@Param("username") String username); }
package com.tszr.jpa.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.tszr.jpa.entity.User; import com.tszr.jpa.dao.UserRepository; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @PostMapping() // 添加 public User saveUser(@RequestBody User user) { // response.setContentType("application/json;charset=UTF-8"); return userRepository.save(user); } @DeleteMapping("/{id}") // 删除 public void deleteUser(@PathVariable("id") int id) { userRepository.deleteById(id); } @PutMapping("/{id}") public User updateUser(@PathVariable("id") int userId, @RequestBody User user) { user.setId(userId); return userRepository.saveAndFlush(user); } @GetMapping("/{id}") public User getUserInfo(@PathVariable("id") int userId) { Optional<User> optional = userRepository.findById(userId); return optional.orElseGet(User::new); } @GetMapping("/list") public Page<User> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize)); } @GetMapping("/ops") public List<User> getOPs(String username) { return userRepository.getUserByUsername(username); } @PostMapping("/login") public User getPerson(String username, String password) { return userRepository.findByUsernameAndPassword(username, password); } }
package com.tszr.jpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }