本文講解 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
(完)
更多精彩文章,盡在「服務端思惟」微信公衆號!