最近又撸了半个月的前端代码,做app离线存储,然后又花了一周去将过去的wcf项目转webapi,java又被落下了,总感觉我特么像斗地主中的癞子牌,变来变去.....
Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。我觉得它就是一个封装好了的泛型仓储。
点击JpaRepository进去看下它的源码:
@NoRepositoryBeanpublicinterfaceJpaRepositoryextendsPagingAndSortingRepository, QueryByExampleExecutor {
List findAll();
List findAll(Sort var1);
List findAll(Iterable var1);
List save(Iterable var1);
void flush();
S saveAndFlush(S var1);
voiddeleteInBatch(Iterable var1);
void deleteAllInBatch();
T getOne(ID var1);
List findAll(Example var1);
List findAll(Example var1, Sort var2);
}
关于JPA的详细介绍请移步:spring boot 中使用 jpa以及jpa介绍
有了前面文章的基础之后,下面的操作就信手捏来了,所以就不做过多的解释。
这里用到了mysql数据库,先运行已经准备好mysql脚本,进行数据库初始化。
SETFOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `tb_book`-- ----------------------------DROPTABLEIFEXISTS `tb_book`;CREATETABLE `tb_book` (
`id` bigint(11)NOTNULL AUTO_INCREMENT,
`bookname` varchar(50)DEFAULTNULLCOMMENT'书名',
`price` decimal(10,0)DEFAULT'0'COMMENT'价格',
`author` varchar(30)DEFAULTNULLCOMMENT'作者',
`publishdate` date DEFAULTNULLCOMMENT'出版日期',
`pagesize` int(11)DEFAULT'0'COMMENT'页数',
PRIMARYKEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULTCHARSET=utf8;-- ------------------------------ Records of tb_book-- ----------------------------INSERTINTO`tb_book`VALUES('1','ASP.NET MVC企业级实战','89','邹琼俊','2017-04-01','476');INSERTINTO`tb_book`VALUES('2','Java疯狂讲义','99','李阳','2016-05-02','890');
修改pom.xml文件,添加jpa引用,当然这里用到了mysql数据库,那么还要添加mysql数据库引用
org.springframework.bootspring-boot-starter-data-jpacom.alibabadruid1.1.0mysqlmysql-connector-javaruntime
修改配置文件application.yml,对数据库和jpa进行配置
spring: profiles: active: dev datasource: name: demo url: jdbc:mysql://127.0.0.1:3306/demo?&useSSL=falseusername: 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。
View Code
创建数据库访问接口IBookRepository,这里继承JPA疯子的泛型接口JpaRepository
package com.yujie.dao;import com.yujie.model.Book;import org.springframework.data.jpa.repository.JpaRepository;publicinterfaceIBookRepositoryextendsJpaRepository {
}
创建控制器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;importorg.springframework.web.bind.annotation.*;
@RestControllerpublicclass BookController {
@Autowired
private IBookRepository repository;
@GetMapping("/book/{id}")
publicBook 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请求)访问的跨域问题
*/@ConfigurationpublicclassCorsConfigextends WebMvcConfigurerAdapter {
@Override
publicvoid 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 = falseVue.use(VueResource)/* eslint-disable no-new */new Vue({ el: '#app', router, components: { App }, template: '',
http:{
root:''
}
})
3.修改BookDetail.vue代码:
书名: 作者: 页数: 定价: 出版日期: 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:[
]
}.bookdetail div{text-align: left;}
运行结果:
网友评论