Spring Data學習(一):初識

前言

Spring Data是爲了簡化數據庫的訪問,支持關係數據庫、非關係數據庫、map-reduce框架和基於雲的數據服務java

添加Spring Data

將SpringData添加進Spring Boot項目中。mysql

配置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會自動根據字段名稱建立。spring

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)sql

建立查詢

下面就是見證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自動根據實體類字段名設置了數據庫裏的字段名。
springboot

碰見問題處理

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時出現的,直接致使系統不能啓動。
具體報錯信息app

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從新獲取一次就行;
maven

參考

官網說明:http://projects.spring.io/spring-data-jpa/ 官網入門示例:https://spring.io/guides/gs/accessing-data-jpa/

相關文章
相關標籤/搜索