• Spring boot JPA 简单配置使用


    JPA 常用配置: 

    # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
    spring.data.jpa.repositories.bootstrap-mode=default # Bootstrap mode for JPA repositories.
    spring.data.jpa.repositories.enabled=true # Whether to enable JPA repositories.
    spring.jpa.database= # Target database to operate on, auto-detected by default. Can be alternatively set using the "databasePlatform" property.
    spring.jpa.database-platform= # Name of the target database to operate on, auto-detected by default. Can be alternatively set using the "Database" enum.
    spring.jpa.generate-ddl=false # Whether to initialize the schema on startup.
    spring.jpa.hibernate.ddl-auto= # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".
    spring.jpa.hibernate.naming.implicit-strategy= # Fully qualified name of the implicit naming strategy.
    spring.jpa.hibernate.naming.physical-strategy= # Fully qualified name of the physical naming strategy.
    spring.jpa.hibernate.use-new-id-generator-mappings= # Whether to use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE.
    spring.jpa.mapping-resources= # Mapping resources (equivalent to "mapping-file" entries in persistence.xml).
    spring.jpa.open-in-view=true # Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request.
    spring.jpa.properties.*= # Additional native properties to set on the JPA provider.
    spring.jpa.show-sql=false # Whether to enable logging of SQL statements.
    

    DataSource 配置:

    # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
    spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database.  
    spring.datasource.data= # Data (DML) script resource references.
    spring.datasource.data-username= # Username of the database to execute DML scripts (if different).
    spring.datasource.data-password= # Password of the database to execute DML scripts (if different).
    spring.datasource.dbcp2.*= # Commons DBCP2 specific settings
    spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
    spring.datasource.generate-unique-name=false # Whether to generate a random datasource name.
    spring.datasource.hikari.*= # Hikari specific settings
    spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts.
    spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool).
    spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set.
    spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database.
    spring.datasource.password= # Login password of the database.
    spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql).
    spring.datasource.schema= # Schema (DDL) script resource references.
    spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different).
    spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different).
    spring.datasource.separator=; # Statement separator in SQL initialization scripts.
    spring.datasource.sql-script-encoding= # SQL scripts encoding.
    spring.datasource.tomcat.*= # Tomcat datasource specific settings
    spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath.
    spring.datasource.url= # JDBC URL of the database.
    spring.datasource.username= # Login username of the database.
    spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name.
    spring.datasource.xa.properties= # Properties to pass to the XA data source.

    目录结构

    1. pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <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.0</modelVersion>
    
        <groupId>com.springtest</groupId>
        <artifactId>myspringtest1</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.5.RELEASE</version>
        </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-thymeleaf</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
                <version>2.1.5.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>6.0.6</version>
            </dependency>
    
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    2. logback-spring.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
    <!-- scan:当此属性设置为true时,配置文档如果发生改变,将会被重新加载,默认值为true -->
    <!-- scanPeriod:设置监测配置文档是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。
                     当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
    <!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
    <configuration  scan="true" scanPeriod="10 seconds">
        <contextName>logback</contextName>
    
        <springProfile name="dev">
            <property name="log.path" value="/Users/guoxiwang/software/idea/log/dev" />
        </springProfile>
        <springProfile name="prd">
            <property name="log.path" value="/Users/guoxiwang/software/idea/log/prd" />
        </springProfile>
    
        <!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义后,可以使“${}”来使用变量。 -->
    <!--    <property name="log.path" value="/Users/guoxiwang/software/idea/log" />-->
    
        <!--0. 日志格式和颜色渲染 -->
        <!-- 彩色日志依赖的渲染类 -->
        <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
        <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
        <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
        <!-- 彩色日志格式 -->
        <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    
        <!--1. 输出到控制台-->
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
            <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
                <level>debug</level>
            </filter>
            <encoder>
                <Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
                <!-- 设置字符集 -->
                <charset>UTF-8</charset>
            </encoder>
        </appender>
    
        <!--2. 输出到文档-->
        <!-- 2.1 level为 DEBUG 日志,时间滚动输出  -->
        <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 正在记录的日志文档的路径及文档名 -->
            <file>${log.path}/web_debug.log</file>
            <!--日志文档输出格式-->
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset> <!-- 设置字符集 -->
            </encoder>
            <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 日志归档 -->
                <fileNamePattern>${log.path}/web-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>1MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <!--日志文档保留天数-->
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <!-- 此日志文档只记录debug级别的 -->
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>debug</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <!-- 2.2 level为 INFO 日志,时间滚动输出  -->
        <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 正在记录的日志文档的路径及文档名 -->
            <file>${log.path}/web_info.log</file>
            <!--日志文档输出格式-->
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset>
            </encoder>
            <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 每天日志归档路径以及格式 -->
                <fileNamePattern>${log.path}/web-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>100MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <!--日志文档保留天数-->
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <!-- 此日志文档只记录info级别的 -->
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>info</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <!-- 2.3 level为 WARN 日志,时间滚动输出  -->
        <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 正在记录的日志文档的路径及文档名 -->
            <file>${log.path}/web_warn.log</file>
            <!--日志文档输出格式-->
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset> <!-- 此处设置字符集 -->
            </encoder>
            <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log.path}/web-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>1MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <!--日志文档保留天数-->
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <!-- 此日志文档只记录warn级别的 -->
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>warn</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <!-- 2.4 level为 ERROR 日志,时间滚动输出  -->
        <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 正在记录的日志文档的路径及文档名 -->
            <file>${log.path}/web_error.log</file>
            <!--日志文档输出格式-->
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset> <!-- 此处设置字符集 -->
            </encoder>
            <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log.path}/web-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>1MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
                <!--日志文档保留天数-->
                <maxHistory>15</maxHistory>
            </rollingPolicy>
            <!-- 此日志文档只记录ERROR级别的 -->
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>ERROR</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <!--
            <logger>用来设置某一个包或者具体的某一个类的日志打印级别、
            以及指定<appender>。<logger>仅有一个name属性,
            一个可选的level和一个可选的addtivity属性。
            name:用来指定受此logger约束的某一个包或者具体的某一个类。
            level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
                  还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
                  如果未设置此属性,那么当前logger将会继承上级的级别。
            addtivity:是否向上级logger传递打印信息。默认是true。
            <logger name="org.springframework.web" level="info"/>
            <logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>
        -->
    
        <!--
            使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
            第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
            第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
            【logging.level.org.mybatis=debug logging.level.dao=debug】
         -->
    
        <!--
            root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
            level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
            不能设置为INHERITED或者同义词NULL。默认是DEBUG
            可以包含零个或多个元素,标识这个appender将会添加到这个logger。
        -->
    
        <!-- 4. 最终的策略 -->
        <!-- 4.1 开发环境:打印控制台-->
        <springProfile name="dev">
            <logger name="com.springtest.mytest1" level="debug"/>
        </springProfile>
    
        <root level="info">
            <appender-ref ref="CONSOLE" />
            <appender-ref ref="DEBUG_FILE" />
            <appender-ref ref="INFO_FILE" />
            <appender-ref ref="WARN_FILE" />
            <appender-ref ref="ERROR_FILE" />
        </root>
    
        <!-- 4.2 生产环境:输出到文档
        <springProfile name="pro">
            <root level="info">
                <appender-ref ref="CONSOLE" />
                <appender-ref ref="DEBUG_FILE" />
                <appender-ref ref="INFO_FILE" />
                <appender-ref ref="ERROR_FILE" />
                <appender-ref ref="WARN_FILE" />
            </root>
        </springProfile> -->
    </configuration>
    

     

    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8
        username: root
        password: 12345678
      jpa:
        show-sql: true
        generate-ddl: true
        hibernate:
          ddl-auto: update
    server:
      port: 8070
    

      

     

    3. RestController

    package com.springtest.mytest1.controller;
    
    
    import com.springtest.mytest1.entity.CustomUser;
    import com.springtest.mytest1.model.User;
    import com.springtest.mytest1.repo.CustomUserRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import java.util.List;
    
    @org.springframework.web.bind.annotation.RestController
    @RequestMapping(path = "/test")
    public class RestController {
    
    
    
    
        @Autowired
        CustomUserRepository customUserRepository;
    
    
        @RequestMapping(path = "/get",method = RequestMethod.GET)
        public CustomUser getUserName(){
    
    
            CustomUser data=customUserRepository.findOneByName("guoxw");
    
            return data;
    
        }
    
        @RequestMapping(path = "/getStr" ,method = RequestMethod.GET)
        public String getString(){
    
            return "111";
        }
    
    
        @RequestMapping(path = "/getAll")
        public List<CustomUser>getAll(){
            return customUserRepository.findAll();
        }
    
        /**
         *
         * @param name 简单的查询  finByName
         *
         * @return
         */
        @RequestMapping(path = "/findByName")
        public CustomUser findByName(@RequestParam  String name){
    
            return  customUserRepository.findByName(name);
    
        }
    
    
        /**
         *
         * @param user
         * @return
         */
        @RequestMapping(path = "/user", method = RequestMethod.POST)
        public User TestUserCreate(@RequestBody User user) {
            // logger.debug("Request body is: {}", user);
    
    
            return user;
        }
    
    
        @RequestMapping(path = "/add",method = RequestMethod.POST)
        public void  CreateCustomUer(@RequestBody CustomUser user){
    
            customUserRepository.save(user);
            return;
    
        }
    
    
        @RequestMapping(path = "/findByUserId",method = RequestMethod.POST)
        public CustomUser findByUserId(@RequestParam Long id){
    
           // return  customUserRepository.findByUserId(id);
    
            return null;
        }
    
    
        @RequestMapping(path = "/update",method = RequestMethod.POST)
        public void updateById(@RequestParam  String  name){
    
              customUserRepository.updateByName(name);
              return;
        }
    
    
        @RequestMapping(path = "/del",method = RequestMethod.POST)
        public void  delById(@RequestParam long id){
    
           //customUserRepository.delByUserId(id);
    
        }
    
    
    }
    

    4.CustomUser

    package com.springtest.mytest1.entity;
    import javax.persistence.*;
    import java.io.Serializable;
    
    @Entity(name = "custom_user")
    public class CustomUser implements Serializable {
    
    
        @Id
        @GeneratedValue (strategy = GenerationType.IDENTITY)
        @Column(name = "custom_id",unique = true)
        private Long id;
    
        @Column(name = "custom_name")
        private String name;
    
        @Column(name = "custom_age")
        private int age;
    
        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 int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    

      

    5. CustomRepository 

    package com.springtest.mytest1.repo;
    
    import com.springtest.mytest1.entity.CustomUser;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;
    
    @Repository
    public interface CustomUserRepository extends JpaRepository<CustomUser,Long> {
    
         CustomUser findOneByName(String name);
    
    
    
    
        /***
         *
         * @param name   CustomUser 里面的字段
         *
         * @return
         */
         CustomUser findByName(String name);
    
    //     @Query("select u from custom_user  u where u.age= ? 18")
    //     CustomUser findByUserId(Long id);
    //
    //     @Transactional
    //     @Modifying
    //     @Query("delete from custom_user u where id=? 18 ")
    //     void  delByUserId(Long id);
    
    
    
    
         @Transactional(timeout = 10)
         @Modifying
         @Query("update custom_user  u set u.name='guoxw_3'  where u.name='guoxw_2' ")  // 在这里的 custom_user 使用的是 Entity name里面的属性,即是数据库表明,但是 u.name这里的name是实体类的属性,
      // 并不是数据库里面的字段名称

      void updateByName(String name); }

     

      /***
         *
         * @param name   CustomUser 里面的字段
         *
         * @return
         */
         CustomUser findByName(String name);
    
         @Query("select u from custom_user  u where u.id=1")  
         CustomUser findByUserId(@Param("ID") Long ID);
    

      

     

     

     

    JPA 使用

    http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html

     code: idea_code的副本

    JPA

    占位符 ?1 表示传入的第一个参数
    nativeQuery = true 表示原生sql 语句
    不加 nativeQuery = true则sql 语句中是entity 的属性字段
    不加 nativeQuery =true JPA 不能使用insert 语句

     
    public interface CustomRepository extends JpaRepository<CustomUser,Long> {
    
    
        //  占位符 ?1 表示传入的第一个参数
        //  nativeQuery = true 表示原生sql 语句
        //  不加 nativeQuery = true则sql 语句中是entity 的属性字段
        //  不加 nativeQuery =true JPA 不能使用insert 语句
        @Modifying
        @Query(value = "select   user from  CustomUser  user where user.id >?1 and user.age>?2")
        List<CustomUser> findCustomById(int user_id, int age);
    
        @Modifying
        @Transactional
        @Query(value = "insert custom_user (custom_name,custom_age) values(?1,?2) " ,nativeQuery = true)
        void  addCustomUser(String name,int age);
    
    
        @Modifying
        @Transactional(noRollbackFor = Exception.class)
        @Query(value = "delete  from  custom_user where custom_id=?1", nativeQuery = true)
        void delUser(int id);
    
        @Modifying
        @Transactional(noRollbackFor = Exception.class)
        @Query(value = "update  custom_user set custom_name=?2 where  custom_id=?1",nativeQuery = true)
        void update(int id ,String name);
    
    
        @Modifying
        @Transactional
        @Query(value = "select   * from  custom_user ",nativeQuery = true)
        List<Map<String,Object>> findAllUser();
    
    
    
    }
    
    @Entity
    @Table(name = "custom_user")   // 生成的数据表的名称是 custom_user
    public class CustomUser {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "custom_id")
        public  int id;
    
    
        @Column(name = "custom_name")
        public String name;
    
    
        @Column(name ="custom_age")
        public  int age;
    
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    

    联合查询

    <?xml version="1.0" encoding="UTF-8"?>
    <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.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.gail</groupId>
        <artifactId>jpa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>jpa</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.20</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

      

    数据表 course

    @Entity
    @Table(name = "course")
    public class Course {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        public  int id;
    
    
        @Column(name = "user_grade")
        public int userGrade;
    
    
        @Column(name = "user_id")
        public int userId;
    
    
        @Column(name = "grade_name")
        public  String gradeName;
    }
    

     

    数据表 student

    @Entity
    @Table(name = "student")
    public class Student {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        public int id;
    
    
        @Column(name = "user_id")
        public int userId;
    
    
        @Column(name = "user_name")
        public String userName;
    
        @Column(name = "user_age")
        public int userAge;
    } 

    实体类:StudentCourse

    public class StudentCourse {
    
        private int userId;
    
        private String userName;
    
        private int userAge;
    
        private String gradeName;
    
        private int userGrade;
    }
    

      

     

    JPA 多表联合查询 返回List<Map<String,Object>>对象

    @Repository
    public interface  AccountRepository  extends JpaRepository<Course,Integer> {
    
        @Query(value = "select s.user_id,s.user_name,s.user_age,c.grade_name,c.user_grade " +
                "from course  c left join  student s  on (c.user_id=s.user_id && s.user_id=?1)", nativeQuery = true)
        List<Map<String,Object>> getStudentCourse(int userId);
    
    }
    

      

     

    Jpa 联合查询,自定义 JpaRepository  返回List<Class>对象 

    @Repository
    public class StudentCourseRepo {
    
        @Autowired
        private NamedParameterJdbcTemplate template;
    
        private static final String queryString = "select s.user_id,s.user_name,s.user_age,c.grade_name,c.user_grade " +
                "from course  c left join  student s  on (c.user_id=s.user_id && s.user_id= :userId)";
    
        public List<StudentCourse> queryStudentCource(int userId) {
            MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource().addValue("userId", userId);
    
            return template.query(queryString, mapSqlParameterSource, (ResultSet rs, int row) -> {
                StudentCourse sc = new StudentCourse();
                sc.setUserId(rs.getInt("user_id"));
                sc.setGradeName(rs.getString("grade_name"));
                return sc;
            });
        }
    }
    

      

     

  • 相关阅读:
    deepin-wine-tim 字体发虚
    windows&linux双系统时间相差8小时
    Linux 禁用 ipv6
    双系统win10更新后无法进入linux
    Failed to receive SOCKS4 connect request ack 解决
    zsh 使用通配符功能
    vux修改css样式的2种办法
    Ubuntu 16.04 安装OpenSSH7.4
    Nginx开启http2访问和gzip网页压缩功能
    vue开发环境和生产环境里面解决跨域的几种方法
  • 原文地址:https://www.cnblogs.com/galibujianbusana/p/11074350.html
Copyright © 2020-2023  润新知