spring boot jpa 查询无主键的视图

spring boot jpa 查询无主键的视图

文章目录

  • spring boot jpa 查询无主键的视图
    • pom.xml
    • application.properties
    • log4j.properties
    • log4j2-spring.xml
    • bean
    • druid
    • repository
    • testRepository

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.3.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.companygroupId>
    <artifactId>demostaffartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demostaffname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-starter-loggingartifactId>
                exclusion>
            exclusions>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-log4j2artifactId>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.15version>
        dependency>
        
        <dependency>
            <groupId>com.lmaxgroupId>
            <artifactId>disruptorartifactId>
            <version>3.4.2version>
        dependency>
        
        <dependency>
            <groupId>com.sun.xml.bindgroupId>
            <artifactId>jaxb-implartifactId>
            <version>2.2.3-1version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>org.postgresqlgroupId>
            <artifactId>postgresqlartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.10version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

application.properties

####################################################################
###durid
###驱动配置信息
spring.datasource.url=jdbc:postgresql://10.96.32.40:7017/isfd_isfddb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=user_oa
spring.datasource.password=Flzx3qc
spring.datasource.driver-class-name=org.postgresql.Driver
###连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select version()
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
####################################################################
###还需要log4j配置:
log4j.rootCategory=INFO, stdout
log4j.rootLogger=info, stdout
### stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p - %m%n
### set package ###
log4j.logger.org.springframework=info
log4j.logger.org.apache.catalina=info
log4j.logger.org.apache.commons.digester.Digester=info
log4j.logger.org.apache.catalina.startup.TldConfig=info
log4j.logger.chb.test=debug
####################################################################
###spring data jpa底层使用hibernate
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
spring.jpa.show-sql=true

log4j.properties

#### 设置 ###
#log4j.rootLogger=info,debug,stdout,D,E
#### 输出信息到控制抬 ###
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.out
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
#### 输出INFO 级别以上的日志到=D://error.log ###
#log4j.appender.D=org.apache.log4j.RollingFileAppender
#log4j.appender.D.File=/opt/lb/facelinkmac3/debug_log.txt
#log4j.appender.D.Append=true
#log4j.appender.D.Threshold=DEBUG
#log4j.appender.D.layout=org.apache.log4j.PatternLayout
#log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
#### 输出ERROR 级别以上的日志到=E://logs/error.log ###
#log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.E.File=/opt/lb/facelinkmac3/error_log.txt
#log4j.appender.E.Append=true
#log4j.appender.E.Threshold=ERROR
#log4j.appender.E.layout=org.apache.log4j.PatternLayout
#log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
### 设置 ###
log4j.rootLogger=info,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yy-MM-dd HH:mm:ss} %p %c{1}: %m%n
### 输出INFO级别以上的日志到指定文件###
log4j.appender.D=org.apache.log4j.RollingFileAppender
log4j.appender.D.File=/opt/lb/facelinkmac0/log/debug.log
#log4j.appender.D.File=D:\\a02_allcode\\p181226_scala2sparkml\\scala2spark4ml\\src\\main\\resources\\log\\debug.log
log4j.appender.D.Append=true
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%d{yy-MM-dd HH:mm:ss} %p %c{1}: %m%n
### 输出ERROR级别以上的日志到指定文件###
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File=/opt/lb/facelinkmac0/log/error.log
#log4j.appender.E.File=D:\\a02_allcode\\p181226_scala2sparkml\\scala2sparkml\\src\\main\\resources\\log\\error.log
log4j.appender.E.Append=true
log4j.appender.E.Threshold=ERROR
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%d{yy-MM-dd HH:mm:ss} %p %c{1}: %m%n

log4j2-spring.xml


<configuration status="debug">
    <Properties>
        
        <Property name="LOG_HOME">D:/build/house/house-service/logsProperty>
        
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level [%logger{50}:%L] [%X{X-B3-TraceId},%X{X-B3-SpanId}] - %msg%nProperty>
    Properties>
    <appenders>
        
        <Console name="STDOUT">
            
            <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
            
            <PatternLayout pattern="${LOG_PATTERN}" charset="utf-8"/>
        Console>

        <RollingRandomAccessFile name="FILE-INFO" fileName="${LOG_HOME}/house-info.log" filePattern="${LOG_HOME}/house-info.%d{yyyy-MM-dd-HH}.log">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}" charset="UTF-8"/>
            <TimeBasedTriggeringPolicy interval="1"/>
            <DefaultRolloverStrategy max="1">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="*house-info.*.log"/>
                    <IfLastModified age="1h"/>
                Delete>
            DefaultRolloverStrategy>
        RollingRandomAccessFile>

        <RollingRandomAccessFile name="FILE-DEBUG" fileName="${LOG_HOME}/house-debug.log" filePattern="${LOG_HOME}/house-debug.%d{yyyy-MM-dd-HH}.log">
            <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}" charset="UTF-8"/>
            <TimeBasedTriggeringPolicy interval="1"/>
            <DefaultRolloverStrategy max="1">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="*house-debug.*.log"/>
                    <IfLastModified age="1h"/>
                Delete>
            DefaultRolloverStrategy>
        RollingRandomAccessFile>

        <RollingRandomAccessFile name="FILE-WARN" fileName="${LOG_HOME}/house-warn.log" filePattern="${LOG_HOME}/house-warn.%d{yyyy-MM-dd-HH}.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}" charset="UTF-8"/>
            <TimeBasedTriggeringPolicy interval="1"/>
            <DefaultRolloverStrategy max="1">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="*house-warn.*.log"/>
                    <IfLastModified age="1h"/>
                Delete>
            DefaultRolloverStrategy>
        RollingRandomAccessFile>

        <RollingRandomAccessFile name="FILE-ERROR" fileName="${LOG_HOME}/house-error.log" filePattern="${LOG_HOME}/house-error.%d{yyyy-MM-dd-HH}.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}" charset="UTF-8"/>
            <TimeBasedTriggeringPolicy interval="1"/>
            <DefaultRolloverStrategy max="1">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="*house-error.*.log"/>
                    <IfLastModified age="1h"/>
                Delete>
            DefaultRolloverStrategy>
        RollingRandomAccessFile>
    appenders>

    <loggers>
        <AsyncLogger name="springfox" level="OFF"/>
        <AsyncLogger level="DEBUG" name="com.house.house.mapper" additivity="false">
            <appender-ref ref="FILE-DEBUG"/>
            <appender-ref ref="STDOUT"/>
        AsyncLogger>
        <AsyncRoot level="INFO" includeLocation="true">
            <AppenderRef ref="FILE-INFO"/>
            <AppenderRef ref="FILE-WARN"/>
            <AppenderRef ref="FILE-ERROR"/>
            <AppenderRef ref="STDOUT"/>
        AsyncRoot>
    loggers>
configuration>

bean

package com.company.demostaff.bean;

import lombok.*;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
@Entity
@Table(name = "v_get_persion_info")
public class Staff implements Serializable {
    @Id
    @Column(name = "person_id")
    private String personId;
    @Column(name = "person_name")
    private String personName;
    @Column(name = "org_path")
    private String orgPath;
    @Column(name = "face_url")
    private String faceUrl;
    @Column(name = "status")
    private Integer status;
}

druid

package com.company.demostaff.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration

public class DruidDataSourceConfiguration {
    private Logger logger = LoggerFactory.getLogger(DruidDataSourceConfiguration.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;

    /**
     * 初始化DataSource
     *
     * @return
     */
    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter,[{}]", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
}

repository

package com.company.demostaff.repository;

import com.company.demostaff.bean.Staff;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StaffRepository extends JpaRepository<Staff, String> {
    @Query(value = "select * from v_get_persion_info", nativeQuery = true)
    List<Staff> findStaffs();
}

testRepository

package com.company.demostaff.service;

import com.company.demostaff.bean.Staff;
import com.company.demostaff.repository.StaffRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class XXX implements ApplicationRunner {
    @Autowired
    private StaffRepository staffRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<Staff> staff = staffRepository.findStaffs();
        System.out.println(staff.size());
    }
}

你可能感兴趣的:(spring)