前言

Spring Data是为了简化数据库的访问,支持关系数据库、非关系数据库、map-reduce框架和基于云的数据服务

添加Spring Data

将SpringData添加进Spring Boot项目中。

配置pom.xml

<!--会下载所有Spring Data Jpa所需的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

配置数据库相关信息(application.properties)

配置数据库信息

# Mysql属性配置,Spring-boot系统配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

配置自动根据实体类在数据库创建表

# create----每次运行该程序,没有表格会新建表格,表内有数据会清空
# create-drop----每次程序结束的时候会清空表
# update----每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
# validate----运行程序会校验数据与数据库的字段类型是否相同,不同会报错
spring.jpa.hibernate.ddl-auto=update
# 运行时数据SQL语句
spring.jpa.show-sql = true

创建User.java

说明:若是不填写各字段在数据库里的列名,Spring Data会自动根据字段名称创建。

package com.jc.springdata.dao;

import javax.persistence.*;

/**
* Created by Administrator on 2018/7/31.
*/
@Entity //表示是一个JPA实体类
@Table(name = "SBD_USER") //映射的表名称
public class User { @Id // 表示为ID
@GeneratedValue(strategy = GenerationType.AUTO) //自动生成
private Long id; @Column(length = 25)
private String name; @Column(length = 20) //为设置数据库里的字段名称,Spring Data会自动根据实体类字段名称设置,默认为:birthy_day
private String birthyDay; public User() {
} public User(String name, String birthyDay) {
this.name = name;
this.birthyDay = birthyDay;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getBirthyDay() {
return birthyDay;
} public void setBirthyDay(String birthyDay) {
this.birthyDay = birthyDay;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", birthyDay='" + birthyDay + '\'' +
'}';
}
}

ps:添加java实体类时,可以考虑使用lombok(https://www.cnblogs.com/wsygdb/p/9467690.html)

创建查询

下面就是见证Spring Data神奇的时候了,即:您不必编写存储库接口的实现。Spring Data JPA在运行应用程序时动态创建一个实现。

创建一个关于对User表的查询接口IUserRepository.java

import com.jc.springdata.dao.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository; import java.util.List; /**
* Created by Administrator on 2018/8/2.<br/>
* 特别说明:这正是Spring Data JPA如此强大的原因:您不必编写存储库接口的实现。Spring Data JPA在运行应用程序时动态创建一个实现。
*/
@Repository("userRepository") //表明该类是用来执行与数据库相关的操作(即dao对象),并支持自动处理数据库操作产生的异常
public interface IUserRepository extends CrudRepository<User,Long> { // 参数1:表示数据表对应的实体类,参数2:主键的类型 /**
* 根据名称查找用户</>
* @param name
* @return
*/
List<User> findByName(String name); /**
* 根据生日查询对应的用户
* @param birthyDay
* @return
*/
List<User> findByBirthyDay(String birthyDay); }

测试

1) 创建UserCommandLineRunner.java,实现CommandLineRunner.java接口,用户在SpringBoot启动时运行

package com.jc.springdata.runner;

import com.jc.springdata.dao.User;
import com.jc.springdata.mgr.IUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; /**
* Created by Administrator on 2018/8/3.
*/
@Order(value = 1) //系统启动的优先级
@Component
public class UserCommandLineRunner implements CommandLineRunner{ private static final Logger LOG = LoggerFactory.getLogger(UserCommandLineRunner.class); @Autowired
private IUserRepository userRepository; @Override
public void run(String... args) throws Exception {
LOG.info("---- start save ----");
userRepository.save(new User("Tom","20150101"));
userRepository.save(new User("Jack","20050101"));
userRepository.save(new User("SuSan","20000101")); LOG.info("---- find all ----");
Iterable<User> users = userRepository.findAll();
for (User user: users) {
LOG.info("user:{}",user);
}
} }

2) 启动Spring Boot

再次启动SpringBoot,查看启动日志,发现系统有创建表的sql、查询等被执行的SQL:



这是系统查询



查看数据库,确实是自动创建了表,可以看到,由于我们未给各个字段设置数据库里的字段名,Spring Data自动根据实体类字段名设置了数据库里的字段名。

遇见问题处理

Failed to read Class-Path attribute from manifest of jar file:/../repository/org/jboss/jandex/2.0.3.Final/jandex-2.0.3.Final.jar

报错是在启动SpringBoot时出现的,直接导致系统不能启动。

具体报错信息

Exception in thread "main" java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/xx/maven/repository/org/jboss/jandex/2.0.3.Final/jandex-2.0.3.Final.jar
at org.springframework.boot.devtools.restart.ChangeableUrls.getUrlsFromClassPathOfJarManifestIfPossible(ChangeableUrls.java:132)
at org.springframework.boot.devtools.restart.ChangeableUrls.fromClassLoader(ChangeableUrls.java:98)
at org.springframework.boot.devtools.restart.DefaultRestartInitializer.getUrls(DefaultRestartInitializer.java:91)
at org.springframework.boot.devtools.restart.DefaultRestartInitializer.getInitialUrls(DefaultRestartInitializer.java:55)
at org.springframework.boot.devtools.restart.Restarter.<init>(Restarter.java:142)
at org.springframework.boot.devtools.restart.Restarter.initialize(Restarter.java:556)
at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationStartingEvent(RestartApplicationListener.java:67)
at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationEvent(RestartApplicationListener.java:45)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:68)
at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
at com.jc.SpringbootdemoApplication.main(SpringbootdemoApplication.java:11)
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
at java.util.zip.ZipFile.read(Native Method)
at java.util.zip.ZipFile.access$1400(ZipFile.java:60)
at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:717)
at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:419)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at sun.misc.IOUtils.readFully(IOUtils.java:65)
at java.util.jar.JarFile.getBytes(JarFile.java:425)
at java.util.jar.JarFile.getManifestFromReference(JarFile.java:193)
at java.util.jar.JarFile.getManifest(JarFile.java:180)
at org.springframework.boot.devtools.restart.ChangeableUrls.getUrlsFromManifestClassPathAttribute(ChangeableUrls.java:153)
at org.springframework.boot.devtools.restart.ChangeableUrls.getUrlsFromClassPathOfJarManifestIfPossible(ChangeableUrls.java:129)
... 17 more

原因分析

maven本地库中指定的jar文件有问题。

处理方法

stap 1:删除指定目录内的jar文件(/xx/maven/repository/org/jboss/jandex/2.0.3.Final/jandex-2.0.3.Final.jar);

step 2:然后让Maven重新获取一次就行;

参考

官网说明:http://projects.spring.io/spring-data-jpa/

官网入门示例:https://spring.io/guides/gs/accessing-data-jpa/

Spring Data学习(一):初识的更多相关文章

  1. spring data学习

    在Spring Data模块中定义依赖: <dependencies> <dependency> <groupId>org.springframework.data ...

  2. Spring Data学习中心

    Spring Data 概览 Spring Data的使命是为数据访问提供熟悉且一致的基于Spring的编程模型,同时仍保留底层数据存储的特殊特性. 它使数据访问技术,关系数据库和非关系数据库,map ...

  3. JavaEE高级-Spring Data学习笔记

    Spring Data概述 - Spring Data : Spring 的一个子项目.用于简化数据库访问,支持NoSQL 和 关系数据存储.其主要目标是使数据库的访问变得方便快捷. - Spring ...

  4. Spring基础学习(一)—初识Spring

    一.Spring的使用 1.导入jar包 2.编写实体类 Person.java public class Person{ private String name; public void say() ...

  5. 1.1(Spring MVC学习笔记)初识SpringMVC及SpringMVC流程

    一.Spring MVC Spring MVC是Spring提供的一个实现了web MVC设计模式的轻量级Web框架. Spring优点:网上有,此处不复述. 二.第一个Spring MVC 2.1首 ...

  6. 一步步学习 Spring Data 系列之JPA(一)

    引入: Spring Data是SpringSource基金会下的一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得数据库的访问变得方便快捷,并支持map-reduce框架和云计算数据服 ...

  7. 一步步学习 Spring Data 系列之JPA(二)

    继上一篇文章对Spring Data JPA更深( )一步剖析. 上一篇只是简单的介绍了Spring Data JPA的简单使用,而往往在项目中这一点功能并不能满足我们的需求.这是当然的,在业务中查询 ...

  8. Spring Data JPA 学习记录1 -- 单向1:N关联的一些问题

    开新坑 开新坑了(笑)....公司项目使用的是Spring Data JPA做持久化框架....学习了一段时间以后发现了一点值得注意的小问题.....与大家分享 主要是针对1:N单向关联产生的一系列问 ...

  9. spring data jpa入门学习

    本文主要介绍下spring data jpa,主要聊聊为何要使用它进行开发以及它的基本使用.本文主要是入门介绍,并在最后会留下完整的demo供读者进行下载,从而了解并且开始使用spring data ...

随机推荐

  1. Oracle 行转列两种方法

    1.新建一个名为TEST表 create table TEST( STUDENT varchar2(20), COURSE varchar2(20), SCORE number); INSERT IN ...

  2. 规避Javascript多人开发函数和变量重名问题

    函数和变量重名始终是一个令人头痛的问题,先讲变量吧,相信了解JS的朋友都知道,在JS中 是没有块级作用域的只有函数作用域,也就是说那些以大括号为界定符的代码块是管不住其中定义 的变量的作用域的,举例: ...

  3. 20181009noip HZ EZ 两校联考trade(优先队列,贪心)

    题面戳这里 思路: 裸的,贪心... 考场上写了一个数据分治(70ptsDP,30pts线段树优化贪心,GG了后30分) 这道题其实很简单的 我们看图: 我们在A时刻买一个东西,在B时刻卖出去,我们可 ...

  4. [Usaco2006 Mar]Mooo 奶牛的歌声(单调栈裸题)

    1657: [Usaco2006 Mar]Mooo 奶牛的歌声 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 961  Solved: 679[Submi ...

  5. java递归 斐波那契数列递归与非递归实现

    递归简单来说就是自己调用自己, 递归构造包括两个部分: 1.定义递归头:什么时候需要调用自身方法,如果没有头,将陷入死循环 2.递归体:调用自身方法干什么 递归是自己调用自己的方法,用条件来判断调用什 ...

  6. jquery如何获取对应表单元素?

    问题描述:我页面中有这样多个表单,我都是这个定义的,当我点击确定按钮时,此时能够获得相对应的表单对象,我该怎么获取到他的两个值呢? 解决方案: 页面元素 <form id="form1 ...

  7. 关于使用array_rand随机取出数组的值

    代码如下 <?php echo "<meta charset='utf-8'/>";//选择解码方式,防止乱码现象 $a = array("abc&qu ...

  8. 模块的使用与orm简介

    目录 1 django中app的概念: 2 模板路径配置: 3 静态文件配置: 4 完整版登录功能 5 get请求和post请求 6 新手三件套总结 7 pycharm连接mysql 8 orm介绍 ...

  9. 谭浩强C语言第四版第九章课后习题7--9题(建立,输出,删除,插入链表处理)

    #include<stdio.h> #include<stdlib.h> #define N sizeof(link) typedef struct stu { struct ...

  10. SAPFiori

    最新SAP Fiori常用事务代码持续更新中...谢谢支持   注意: 以 / 开头的事务码需要加/N或/O进入,否则进不去   SEGW:  创建Gateway Service   /UI2/FLP ...