前言

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. linux 中$ 意思

    grep -n sh$ text.txt   查找文件内容中以 Sh 结尾. grep -n ^a text.txt    文件文件内容中以 a 开头. grep -n ^$ text.txt     ...

  2. python 面向对象类与类之间的关系

    主要内容: 1. 依赖关系 2. 关联关系, 组合关系, 聚合关系 3. 继承关系 4. 类中的特殊成员 引子 大千世界, 万物之间皆有规则和规律,我们的类和对象是对大千世界中的所有事物进行归类. 那 ...

  3. HTML中的【块】与【内嵌】

    块元素与内嵌元素 块的特征 默认独占一行 没有宽度时默认撑满一行 支持所有的css命令 内嵌的特征 同行可以连续跟同类的标签 内容撑开宽度 不支持宽高 不支持上下的内外边距 代码换行被解析 块与内嵌的 ...

  4. doc命令操作数据库(下)

    1.给数据表添加一组数据: 2.给数据表添加多组数据: 3.对数据进行删除和修改: 4.用select查询单个或多个数据信息: 5.去除重复值: 6.查询的各种用法: between的用法: 查询排序 ...

  5. SSM框架搭建步骤

    首先要导入相关的jar包(spring\spring-core\spring-jdbc\spring-aop\spring-context\spring-webmvc\junit\commons-la ...

  6. 基于OMAPL:Linux3.3内核的编译

    基于OMAPL:Linux3.3内核的编译 OMAPL对应3个版本的linux源代码,分别是:Linux-3.3.Linux-2.6.37.Linux2.6.33,这里的差距在于Linux2,缺少SY ...

  7. JAVA判断时间是否在时间区间内

    package com.liying.tiger.test; import java.text.ParseException; import java.text.SimpleDateFormat; i ...

  8. Redis Handle

    package com.jn.baseservice.utils; import com.jn.baseservice.GlobalEntiy.Entity; import com.google.gs ...

  9. hadoop jar x.jar 执行过程

    hadoop jar  x.jar  执行过程 Yarn框架执行内容 1,job.waitforcompletion() 启动 Runjar 进程  -> Resourcemanage申请一个j ...

  10. 【Java】关于Spring框架的总结 (二)

    上文提到了 Spring 的 IoC 特性和 AOP 特性,只提到个别的实现方法.本文将对 IoC 和 AOP 其他方法进行讲解. 多种方式实现依赖注入 1.设值注入 上文中使用的注入方法:通过 se ...