阅读 1701

Spring Boot 揭秘与实战(二) 数据存储篇 - JPA

本文讲解 Spring Boot 基础下,如何整合 JPA 框架,编写数据访问。

博客地址:blog.720ui.com/

环境依赖

修改 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

(完)

更多精彩文章,尽在「服务端思维」微信公众号!

关注下面的标签,发现更多相似文章
评论