1. 程式人生 > >Spring Boot + jpa + oracle 整合及遇到的坑

Spring Boot + jpa + oracle 整合及遇到的坑

組裡大佬擼的程式碼,借鑑簡單的部分

一、maven依賴

只需要三個依賴:springboot , springboot jpa , ojdc。lombok是@slf4j用的,可以簡化日誌程式碼;其中ojdc 如果maven不能下載的話,可以到csdn下載:https://download.csdn.net/download/qq_38113432/10647749

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
	    <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	    <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
            <dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.4</version>
		</dependency>
            <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
</dependencies>
    <build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>    

二、配置檔案

#最簡配置
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@192.168.1.21:1521:assistantdb
spring.datasource.username=assistant
spring.datasource.password=assistant123
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
server.port=8081

不得不提,springboot的約定大於配置真的很強大,幾行程式碼就完成了我們的配置

三、實體類

實體類很簡單,主要就是表名列名別寫錯

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table( name = "FILE_INFO" )
public class FileInfoBean {
    @Column( name = "FILE_NAME" )
    private String fileName;
    @Column( name = "DATE_TIME" )
    @Id
    private String dateTime;
    @Column( name = "MONTH" )
    private String month;
    @Column( name = "FILE_TYPE" )
    private String fileType;
    @Column( name = "FILE_SIZE" )
    private long fileSize;

    public FileInfoBean() {
    }

    public FileInfoBean( String fileName, String month, String dateTime, String fileType, long fileSize ) {
        this.fileName = fileName;
        this.month = month;
        this.dateTime = dateTime;
        this.fileType = fileType;
        this.fileSize = fileSize;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName( String fileName ) {
        this.fileName = fileName;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth( String month ) {
        this.month = month;
    }

    public String getDateTime() {
        return dateTime;
    }

    public void setDateTime( String dateTime ) {
        this.dateTime = dateTime;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType( String fileType ) {
        this.fileType = fileType;
    }

    public long getFileSize() {
        return fileSize;
    }

    public void setFileSize( long fileSize ) {
        this.fileSize = fileSize;
    }

}

四、Repository介面

繼承JpaRepository,新增想要的方法;這裡就是按月份和檔案型別分頁查詢

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface FileInfoRepository extends JpaRepository< FileInfoBean, String > {
    Page< FileInfoBean > findAllByMonthAndFileType( String month, String fileType, Pageable pageable );
}

五、Controller類


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 查詢檔案資訊
 */
@RestController
@Slf4j
public class FileInfoController {

    private FileInfoRepository FileInfoRepository;

    private ObjectMapper mapper;

    public FileInfoController( FileInfoRepository FileInfoRepository, ObjectMapper mapper ) {
        this.FileInfoRepository = FileInfoRepository;
        this.mapper = mapper;
    }

    @RequestMapping( "/getFileInfoLog" )
    @ResponseBody
    public String getFileInfoLog( @RequestParam( value = "page_index", required = false, defaultValue = "1" ) Integer pageNum,
                                       @RequestParam( value = "page_total", required = false, defaultValue = "20" ) Integer pageSize,
                                       @RequestParam( value = "file_type", defaultValue = "log" ) String fileType,
                                       @RequestParam( value = "log_date" ) String month ) {
        log.info( "查詢{}週期歸檔日誌,檔案型別{},分頁資訊:當前第{}頁 - 每頁{}條資料", month, fileType, pageNum, pageSize );
        // 初始化返回值
        String responseJson = "{}";
        Map< String, Object > result = new HashMap<>( 3 );
        result.put( "result", 500 );
        result.put( "message", "資料轉換失敗!" );
        result.put( "data", new ArrayList<>() );

        // 準備分頁條件
        Pageable pageable = PageRequest.of( pageNum, pageSize, Sort.Direction.DESC, "dateTime" );

        // 查詢結果
        log.info( "查詢歸檔資訊資料..." );
        Page< FileInfoBean > page = FileInfoRepository.findAllByMonthAndAndFileType( month, fileType, pageable );
        log.info( "查詢到{}條歸檔資訊資料", page.getTotalElements() );
        // 組裝返回值
        result.put( "result", 200 );
        result.put( "message", "成功" );
        result.put( "data", page.getContent() );
        try {
            responseJson = mapper.writeValueAsString( result );
        } catch ( JsonProcessingException e ) {
            log.error( "資料轉換失敗!", e );
        }
        log.info( "查詢結果準備完畢,返回結果資料!" );
        return responseJson;
    }
}

接下來就啟動程式訪問介面測試吧,其他的增刪改查是需要呼叫不同的repository就行了

六、遇到的坑

1.        Pageable pageable = PageRequest.of( pageNum, pageSize, Sort.Direction.DESC, "dateTime" );

分頁中的排序欄位用的是bean類中的欄位,不是資料庫表中的欄位,我們用資料庫中的欄位"date_time"就報錯了

"no property name DATE found for ...";

2.jpa中預設用了sql server的方言,使用oracle 的方言需要在application檔案中加入配置

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect