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;
});
}
}

  

 

Spring JPA 简单配置使用的更多相关文章

  1. Spring mvc系列一之 Spring mvc简单配置

    Spring mvc系列一之 Spring mvc简单配置-引用 Spring MVC做为SpringFrameWork的后续产品,Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块 ...

  2. 【hibernate】spring+ jpa + hibername 配置过程遇到的问题

    org.springframework.data.jpa.domain.support.AuditingEntityListener Auditing: 审计:查账Hades:Hades是一个开源库, ...

  3. 02 Spring框架 简单配置和三种bean的创建方式

    整理了一下之前学习Spring框架时候的一点笔记.如有错误欢迎指正,不喜勿喷. 上一节学习了如何搭建SpringIOC的环境,下一步我们就来讨论一下如何利用ioc来管理对象和维护对象关系. <? ...

  4. SPRING+JPA+Hibernate配置方法

    1.applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans ...

  5. Spring talk简单配置

    XMl文件 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://w ...

  6. Spring JPA学习笔记

    目录 什么是JPA? 引入配置 新建一个Entity Bean类 JPA的增删改查 新建操作接口 新建测试类 总结 什么是JPA? 什么是JDBC知道吧?数据库有Mysql,SQL Server,Or ...

  7. spring.jpa.open-view问题

    由ReentrantLock和JPA(spring.jpa.open-in-view)导致的死锁问题原因分析. 问题 在压测过程中,发现服务经过一段时间压测之后出现无响应,且无法自动恢复. 分析 从上 ...

  8. ssm简单配置

    MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架. MyBatis 摒除了大部分的JDBC代码.手工设置参数和结果集重获. MyBatis 只使用简单的XML 和注解来配置和映射 ...

  9. Spring Boot访问mysql(JPA方式)最简单配置

    0.先推荐一个工具--lombok,pom文件如下: <dependency> <groupId>org.projectlombok</groupId> <a ...

随机推荐

  1. uva 524(Prime Ring Problem UVA - 524 )

    dfs练习题,我素数打表的时候j=i了,一直没发现实际上是j=i*i,以后可记住了.还有最后一行不能有空格...昏迷了半天 我的代码(紫书上的算法) #include <bits/stdc++. ...

  2. Spring Web MVC常用配置汇总

    pom.xml ============================================================================================ ...

  3. MySQL详细操作

    一.用户管理 -- 创建用户 create user "用户名"@"IP地址" identified by "密码"; "; &q ...

  4. 42.global bucket的使用:单个品牌与所有品牌销量对比

    主要知识点: _global bucket的使用     本例以搜索单个品牌和所有品牌的销量对比进行学习_global .es在进行aggregation操作时都只只是在一个scope中进行聚合等操作 ...

  5. CI笔记

    1.控制器 实现自己的控制器MY_Controller是在./application/core/MY_Controller.php中. 2.类库 添加自己的类是放在./application./lib ...

  6. Spring中Bean的作用域差别

    我觉得servlet和spring交叉起来,理解得快. Bean的作用域中,prototype和singleton作用域效果不一样,前者每次都会有新的实例,而后者始终一个实例 . 所以,java.ut ...

  7. DELPHI RTTI实现非可视的功能插件

    思路:通过数据字典定义BPL包名,然后定义BPL包里面的类名,然后定义类里面的方法名,最后定义方法的参数值. 可实现动态加载BPL,调用哪个BPL的哪个类的哪个方法并给该方法赋给指定的参数值,如果是函 ...

  8. 在Ubuntu 14.04 上安装 FTP 服务

    1. sudo apt-get update 2. sudo apt-get install vsftpd 3. adduser sammy Assign a password when prompt ...

  9. SQL Server 2012内部原理及故障排除(专栏)

    PROFESSIONAL SQL SERVER® 2012 INTERNALS AND TROUBLESHOOTING一书(可从这里下载).认为内容非常不错.自己也想对SQL Server 2012有 ...

  10. 一个简单RPC框架是怎样炼成的(I)——开局篇

    开场白,这是一个关于RPC的相关概念的普及篇系列,主要是通过一步步的调整,提炼出一个相对完整的RPC框架. RPC(Remote Procedure Call Protocol)--远程过程调用协议, ...