从.Net到Java学习系列目录
最近又撸了半个月的前端代码,做app离线存储,然后又花了一周去将过去的wcf项目转webapi,java又被落下了,总感觉我特么像斗地主中的癞子牌,变来变去.....
Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。我觉得它就是一个封装好了的泛型仓储。
点击JpaRepository进去看下它的源码:
@NoRepositoryBean public interface JpaRepositoryextends Serializable> extends PagingAndSortingRepository , QueryByExampleExecutor { List findAll(); List findAll(Sort var1); List findAll(Iterable var1); extends T> Listsave(Iterablevar1); void flush();extends T> S saveAndFlush(S var1); void deleteInBatch(Iterablevar1); void deleteAllInBatch(); T getOne(ID var1); extends T> ListfindAll(Examplevar1);extends T> ListfindAll(Examplevar1, Sort var2); }
关于JPA的详细介绍请移步:spring boot 中使用 jpa以及jpa介绍
有了前面文章的基础之后,下面的操作就信手捏来了,所以就不做过多的解释。
这里用到了mysql数据库,先运行已经准备好mysql脚本,进行数据库初始化。
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `tb_book` -- ---------------------------- DROP TABLE IF EXISTS `tb_book`; CREATE TABLE `tb_book` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `bookname` varchar(50) DEFAULT NULL COMMENT '书名', `price` decimal(10,0) DEFAULT '0' COMMENT '价格', `author` varchar(30) DEFAULT NULL COMMENT '作者', `publishdate` date DEFAULT NULL COMMENT '出版日期', `pagesize` int(11) DEFAULT '0' COMMENT '页数', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tb_book -- ---------------------------- INSERT INTO `tb_book` VALUES ('1', 'ASP.NET MVC企业级实战', '89', '邹琼俊', '2017-04-01', '476'); INSERT INTO `tb_book` VALUES ('2', 'Java疯狂讲义', '99', '李阳', '2016-05-02', '890');
修改pom.xml文件,添加jpa引用,当然这里用到了mysql数据库,那么还要添加mysql数据库引用
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-jpaartifactId> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.1.0version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <scope>runtimescope> dependency>
修改配置文件application.yml,对数据库和jpa进行配置
spring: profiles: active: dev datasource: name: demo url: jdbc:mysql://127.0.0.1:3306/demo?&useSSL=false username: root password: yujie # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 jpa: hibernate: ddl-auto: update show-sql: true jackson: serialization: true
创建实体类Book,创建包model,然后创建类Book,需要注意的是java中没有decimal类型,对,没错,一开始我习惯性的输入decimal,结果果断报错了,然后一查文档,发现要用BigDecimal。
package com.yujie.model; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; @Entity @Table(name = "tb_book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public long id; public String bookname; public BigDecimal price; public String author; public Date publishdate; public int pagesize; public long getId() { return id; } public void setId(int id) { this.id = id; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getPublishdate() { return publishdate; } public void setPublishdate(Date publishdate) { this.publishdate = publishdate; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } @Override public String toString() { return "Book{" + "id=" + id + ", bookname='" + bookname + '\'' + ", price=" + price + ", author='" + author + '\'' + ", publishdate=" + publishdate + ", pagesize=" + pagesize + '}'; } }
创建数据库访问接口IBookRepository,这里继承JPA封装的泛型接口JpaRepository
package com.yujie.dao; import com.yujie.model.Book; import org.springframework.data.jpa.repository.JpaRepository; public interface IBookRepository extends JpaRepository{ }
创建控制器BookController,为了让这个控制器直接变成类似.net 中的webapi,我直接在控制器上面添加注解@RestController,这样返回的就是json数据了。
package com.yujie.controller; import com.yujie.dao.IBookRepository; import com.yujie.model.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class BookController { @Autowired private IBookRepository repository; @GetMapping("/book/{id}") public Book getBookDetail(@PathVariable("id") long id){ return repository.findOne(id); } }
添加跨域配置类CorsConfig
package com.yujie.filter; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 解决前端站点(主要为JavaScript发起的Ajax请求)访问的跨域问题 */ @Configuration public class CorsConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") //允许所有前端站点调用 .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(1728000); } }
运行测试
沿用上一篇vue中引用swiper轮播插件来测试 。
1.安装vue-resource
npm install vue-resource --save
2.在main.js中引入vue-resource
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import VueResource from 'vue-resource' Vue.config.productionTip = false Vue.use(VueResource) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>', http:{ root:'' } })
3.修改BookDetail.vue代码:
<template> <div class="bookdetail"> <div>书名:<span v-text="bookdata.bookname">span>div> <div>作者:<span v-text="bookdata.author">span>div> <div>页数:<span v-text="bookdata.pagesize">span>div> <div>定价:<span v-text="bookdata.price">span>div> <div>出版日期:<span v-text="bookdata.publishdate">span>div> div> template> <script> export default { name: "BookDetail", data(){ return{ id:this.$route.params.id, bookdata:{bookname:'',author:'',price:0,publishdate:'',pagesize:0} } }, created(){ var self=this; this.$http.get("http://localhost:8083/book/"+this.id).then(res=>{ self.bookdata.bookname=res.body.bookname; self.bookdata.author=res.body.author; self.bookdata.price=res.body.price; self.bookdata.publishdate=res.body.publishdate; self.bookdata.pagesize=res.body.pagesize; }); }, props:[ ] } script> <style scoped> .bookdetail div{text-align: left;} style>
运行结果: