本文讲解 Spring Boot 基础下,如何整合 JPA 框架,编写数据访问。javascript
博客地址:blog.720ui.com/java
修改 POM 文件,添加 spring-boot-starter-data-jpa 依赖。mysql
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>复制代码
添加 mysql 依赖。git
<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 中配置数据源信息。github
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 方式配置。spring
@Configuration
@EnableJpaRepositories("com.lianggzone.springboot.action.data.jpa")
@EntityScan("com.lianggzone.springboot.action.data.jpa.entity")
public class JPAConfig {}复制代码
先初始化须要用到的SQL脚本。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;复制代码
建立一个 Author 实体,真实的表名是 t_author,包含 id(自增主键)、 realName、 nickname 字段。springboot
@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方法
}复制代码
数据访问层,经过编写一个继承自 JpaRepository 的接口就能完成数据访问。值得注意的是,这个的 from 对象名,而不是具体的表名。微信
public interface AuthorRepository extends JpaRepository<Author, Long> {
List<Author> findAll();
@Query("from Author where id = :id")
Author findAuthor(@Param("id") Long id);
}复制代码
简单的调用 DAO 相关方法。app
@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);
}
}复制代码
为了展示效果,咱们先定义一组简单的 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;
}
}复制代码
@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方法
}复制代码
数据访问层,经过编写一个调用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();
}
}复制代码
简单的调用 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);
}
}复制代码
为了展示效果,咱们先定义一组简单的 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
(完)
更多精彩文章,尽在「服务端思惟」微信公众号!