springboot(六):spring data jpa使用一

在pom.xml里加入如下依赖:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

创建dto对象:

创建操作数据的Repository对象

JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>

 

从上面可以看出,CustomerRepository继承了JpaRepository之后就拥有了CrudRepository、QueryByExampleExecutor、PagingAndSortingRepository的基本能力了,包括基本的增删改查都有了。

数据库配置

需要在application.properties加上如下参数:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create

这里要注意到最后一行参数spring.jpa.properties.hibernate.hbm2ddl.auto=create,这个参数是为了方便处理数据库表,该属性的值一般有如下几个:

validate 加载hibernate时,验证创建数据库表结构
create 每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。
create-drop 加载hibernate时创建,退出是删除表结构
update 加载hibernate自动更新数据库结构

 教程上写create-drop,就是每次启动都要重新创建表,如果表比较少还好,但是多了就是麻烦,还有初始化数据,我这里写的是create,只完成表的初始化创建即可,后面就不需要关注了。基本的配置已经完成了。 

demo示例

因为比较简单,这里只是简单写几个简单的方法进行测试,这里为了简单方便起见,我讲测试的方法放到Controller内——Customercontroller。

1)、save方法,初始化,保存Customer数据**

 z

 在浏览器房屋:http://localhost:8080/customer/save,数据保存数据

JPA系列:创建查询

1、在CustomerRepository接口中,有如下定义:

2、在CustomerController代码中使用CustomerRepository进行数据查询操作。如下:

3、创建查询的方法名命名指南

同时,查询创建还提供了一些基本的方法命名规则,如下:

其中:In和NotIn也将集合的任何子类作为aparameter和数组或varargs。对于相同逻辑操作符的其他语法版本

参考:
官方文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html
API官方文档:http://docs.spring.io/spring-data/data-jpa/docs/current/api/
JPQL文档:http://www.blogjava.net/calmJava/archive/2011/04/01/347450.html

DEMO示例:https://github.com/icnws/spring-data-jpa-demo

猜你喜欢

转载自www.cnblogs.com/xianshiwang/p/9068583.html