文章目錄
本文講解 Spring Boot 基礎下,如何整合 JPA 框架,編寫數據訪問。
環境依賴
修改 POM 文件,添加 spring-boot-starter-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>
- <version>5.1.35</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.14</version>
- </dependency>
數據源
使用 Spring Boot 默認配置, 在 src/main/resources/application.properties 中配置數據源信息。
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db
- spring.datasource.username=root
- spring.datasource.password=root
通過 Java Config 方式配置。
- @Configuration
- @EnableJpaRepositories("com.lianggzone.springboot.action.data.jpa")
- @EntityScan("com.lianggzone.springboot.action.data.jpa.entity")
- public class JPAConfig {}
腳本初始化
先初始化需要用到的SQL腳本。
- CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
- USE `springboot_db`;
- DROP TABLE IF EXISTS `t_author`;
- CREATE TABLE `t_author` (
- `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶ID',
- `real_name` varchar(32) NOT NULL COMMENT '用戶名稱',
- `nick_name` varchar(32) NOT NULL COMMENT '用戶匿名',
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
JPA 整合方案一 通過繼承 JpaRepository 接口
實體對象
創建一個 Author 實體,真實的表名是 t_author,包含 id(自增主鍵)、 realName、 nickname 字段。
- @Entity
- @Table(name = "t_author")
- public class Author{
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- @Column(name="real_name")
- private String realName;
- @Column(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相關
數據訪問層,通過編寫一個繼承自 JpaRepository 的接口就能完成數據訪問。值得注意的是,這個的 from 對象名,而不是具體的表名。
- public interface AuthorRepository extends JpaRepository<Author, Long> {
- List<Author> findAll();
- @Query("from Author where id = :id")
- Author findAuthor(@Param("id") Long id);
- }
Service相關
簡單的調用 DAO 相關方法。
- @Service("jpa.authorService")
- public class AuthorService {
- @Autowired
- private AuthorRepository authorRepository;
- public List<Author> findAll() {
- return this.authorRepository.findAll();
- }
- public Author findAuthor(Long id){
- return this.authorRepository.findAuthor(id);
- }
- }
Controller相關
為了展現效果,我們先定義一組簡單的 RESTful API 接口進行測試。
- @RestController("jpa.authorController")
- @RequestMapping(value = "/data/jpa/author")
- public class AuthorController {
- @Autowired
- private AuthorService authorService;
- /**
- * 查詢用戶列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String, Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAll();
- Map<String, Object> param = new HashMap<String, Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查詢用戶信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if (author == null) {
- throw new RuntimeException("查詢錯誤");
- }
- return author;
- }
- }
JPA 整合方案二 通過調用 EntityManager 類方法
實體對象
- @Entity
- @Table(name = "t_author")
- public class Author{
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- @Column(name="real_name")
- private String realName;
- @Column(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相關
數據訪問層,通過編寫一個調用EntityManager 類方法。值得注意的是,這個的 from 對象名,而不是具體的表名。
- public interface AuthorDao {
- List<Author> findAll();
- Author findAuthor(Long id);
- }
- @Repository
- public class AuthorDaoImpl implements AuthorDao {
- @PersistenceContext
- private EntityManager entityManager;
- @Override
- public List<Author> findAll() {
- return this.entityManager
- .createQuery("select t from Author t", Author.class)
- .getResultList();
- }
- @Override
- public Author findAuthor(Long id){
- return this.entityManager
- .createQuery("select t from Author t where id = ?", Author.class)
- .setParameter(1, id)
- .getSingleResult();
- }
- }
Service相關
簡單的調用 DAO 相關方法。
- @Service("jpa.authorService2")
- public class AuthorService2 {
- @Autowired
- private AuthorDao authorDao;
- public List<Author> findAll() {
- return this.authorDao.findAll();
- }
- public Author findAuthor(Long id){
- return this.authorDao.findAuthor(id);
- }
- }
Controller相關
為了展現效果,我們先定義一組簡單的 RESTful API 接口進行測試。
- @RestController("jpa.authorController2")
- @RequestMapping(value = "/data/jpa/author2")
- public class AuthorController2 {
- @Autowired
- private AuthorService2 authorService;
- /**
- * 查詢用戶列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String, Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAll();
- Map<String, Object> param = new HashMap<String, Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查詢用戶信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if (author == null) {
- throw new RuntimeException("查詢錯誤");
- }
- return author;
- }
- }
源代碼
相關示例完整代碼: springboot-action
(完)
