当前位置: 首页 > 知识库问答 >
问题:

Spring boot+jpa lazy fetch

干善
2023-03-14

我试过:

  • 具有DTO和不具有DTO对象。
  • 将所有依赖项升级到最新版本。
  • 将@RESTController注释更改为@Controller
  • @Query注释,在存储库中的自定义方法上使用左联接提取
  • @lazy(value=true)
  • @basic(fetch=fetchtype.lazy)
  • @lazyCollection(value=lazyCollectionOption.true)
  • @lazytoone(value=lazytooneoption.no_proxy)
  • @elementCollection(fetch=fetchtype.lazy)
  • 当然,我尝试将fetch=fetchtype.lazy放入@manytomany,@manytoone······注释和级联功能。
  • 使用@PersistenceContext私有EntityManager管理器和createQuery();

最后,我将spring security与CustomUserDetailsService一起使用。当我登录时,它返回用户对象。如果@transactional注释是在ServiceImpl类上,它会急切地获取,但如果删除该注释,它会缓慢地获取,但这只适用于登录。

import hu.pte.clms.model.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor{
}
import hu.pte.clms.model.domain.User;
import hu.pte.clms.repository.UserRepository;
import hu.pte.clms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> listAll(){
        return userRepository.findAll();
    }

    /* And another methods with this scheme */

控制器:

import hu.pte.clms.model.domain.User;
import hu.pte.clms.model.dto.UserDTO;
import hu.pte.clms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class UserController{

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/all", method = RequestMethod.GET)
    public ResponseEntity<List<UserDTO>> listAll(){
        return new ResponseEntity<>(userService.listAll().stream().map(user ->
                new UserDTO(user.getId(), user.getFirstName(), user.getLastName(), user.getCity(), user.getCountry(), user.getBio(), user.getPictureUrl())).collect(Collectors.toList()), HttpStatus.OK);
        }

    @RequestMapping(value = "/auth/user")
    public LoginResult get(){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(!auth.getName().equals("anonymousUser")){
            User user = userService.findByUsername(auth.getName());
            return new LoginResult(auth.getName(), auth.getAuthorities(), user);
        }
        return null;
    }
}

LoginResult:

import hu.pte.clms.model.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

public class LoginResult implements UserDetails{
    private String password;
    private String name;
    private User user;
    private Collection<? extends GrantedAuthority> authorities;

    public LoginResult(String name, Collection<? extends GrantedAuthority> authorities, User user){
        this.name = name;
        this.authorities = authorities;
        this.user = user;
    }

    public LoginResult(String username, String s, boolean b, boolean userNonExpired, boolean credentialsNonExpired, boolean userNonLocked, Collection<? extends GrantedAuthority> authorities){}

    public LoginResult(String username, String password, List<GrantedAuthority> grantedAuthorities){
        this.name = username;
        this.password = password;
        this.authorities = grantedAuthorities;
    }

用户:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import hu.pte.clms.model.domain.relationship.UserSkill;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "USER")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class User implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "USERNAME")
    private String username;

    @Column(name = "PASSWORD")
    private String password;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "AGE")
    private Short age;

    @Column(name = "SEX")
    private String sex;

    @Column(name = "PHONE")
    private String phone;

    @Column(name = "SKYPE")
    private String skype;

    @Column(name = "PRIMARY_EMAIL")
    private String primaryEmail;

    @Column(name = "SECONDARY_EMAIL")
    private String secondaryEmail;

    @Column(name = "CITY")
    private String city;

    @Column(name = "COUNTRY")
    private String country;

    @Column(name = "BIO")
    private String bio;

    @Column(name = "PICTURE_URL")
    private String pictureUrl;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "CONFIG_ID")
    private Config config;

    @JsonIgnore
    @ManyToMany
    @JoinTable(name = "REL_USER_ROLE", joinColumns = {@JoinColumn(name = "USER_ID")}, inverseJoinColumns = {@JoinColumn(name = "ROLE_ID")})
    private List<Role> roles = new ArrayList<>();

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "REL_USER_SECURITY_ROLE", joinColumns = {@JoinColumn(name = "USER_ID")}, inverseJoinColumns = {@JoinColumn(name = "SECURITY_ROLE_ID")})
    private List<SecurityRole> securityRoles = new ArrayList<>();

    @ManyToMany(mappedBy = "user")
    private List<UserSkill> skills = new ArrayList<>();

    @JsonIgnore
    @ManyToMany
    @JoinTable(name = "REL_USER_PROJECT", joinColumns = {@JoinColumn(name = "USER_ID")}, inverseJoinColumns = {@JoinColumn(name = "PROJECT_ID")})
    private List<Project> projects = new ArrayList<>();

    @JsonIgnore
    @OneToMany(mappedBy = "reviewed", cascade = CascadeType.ALL)
    private List<Review> reviews = new ArrayList<>();

 /*Getters & setters*/
import com.fasterxml.jackson.annotation.JsonInclude;
import hu.pte.clms.model.domain.*;
import hu.pte.clms.model.domain.relationship.UserSkill;
import java.util.ArrayList;
import java.util.List;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class UserDTO{

    private Long id;
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    private Short age;
    private String sex;
    private String phone;
    private String skype;
    private String primaryEmail;
    private String secondaryEmail;
    private String city;
    private String country;
    private String bio;
    private String pictureUrl;
    private Config config;
    private List<Role> roles = new ArrayList<>();
    private List<SecurityRole> securityRoles = new ArrayList<>();
    private List<UserSkill> skills = new ArrayList<>();
    private List<Project> projects = new ArrayList<>();
    private List<Review> reviews = new ArrayList<>();

    public UserDTO(){
    }

    public UserDTO(User user){
        this.id = user.getId();
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.firstName = user.getFirstName();
        this.lastName = user.getLastName();
        this.age = user.getAge();
        this.sex = user.getSex();
        this.phone = user.getPhone();
        this.skype = user.getSkype();
        this.primaryEmail = user.getPrimaryEmail();
        this.secondaryEmail = user.getSecondaryEmail();
        this.city = user.getCity();
        this.country = user.getCountry();
        this.bio = user.getBio();
        this.pictureUrl = user.getPictureUrl();
        this.config = user.getConfig();
        this.roles = user.getRoles();
        this.securityRoles = user.getSecurityRoles();
        this.skills = user.getSkills();
        this.projects = user.getProjects();
        this.reviews = user.getReviews();
    }

    public UserDTO(Long id, String firstName, String lastName, String city, String country, String bio, String pictureUrl){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.city = city;
        this.country = country;
        this.bio = bio;
        this.pictureUrl = pictureUrl;
    }
    /*Getters & setters*/
}
import hu.pte.clms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner{

    @Autowired
    private UserService userService;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setShowBanner(false);
        app.setRegisterShutdownHook(true);  
    }

    @Override
    public void run(String... strings) throws Exception{
        userService.listAll();
    }
}
    ...

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
    </dependencies>
spring.datasource:
  url: jdbc:mysql://localhost:3306/clms?autoReconnect=true
  username: clms
  password: clms
  testOnBorrow: true
  validationQuery: SELECT 1
  driverClassName: com.mysql.jdbc.Driver

共有1个答案

窦宏旷
2023-03-14

**对不起,我真的不能写评论,所以我在这里写。

这里我唯一能看到的是服务类中的@Transactional注释,并且需要默认传播。

另外一件事,在Jackson中@jsonignoreProperties和@jsonignore不能一起工作。最好将要忽略的属性放在@jsonignoreproperties中(value={“projects”,“reviews”})

 类似资料:
  • 已与目标VM断开连接,地址:“javadeBug”,传输:“共享内存” 进程已完成,退出代码为0 PessoAcontroller:

  • 使用 springboot 改造 jeesite,只保留最简单的系统配置 。 介绍 1、运行主类,登录  admin/admin com.wolfking.jeesite.WolfkingJeesiteDriver 2、砍掉了所有的冗余的东西,只保留系统配置,数据库脚本 wolfking-jeesite.sql 3、使用 springboot 集成,使用 HikariDataSource 数据源

  • WeChat-SpringBoot 是使用 Spring Boot 开发的微信开发后端脚手架

  • 生产制造执行系统,基于 springBoot 开发。 精益生产+ISA-95 标准。 结合 MESA 战略计划方向设计框架。

  • 一个简单便捷的基于springboot+RabbitMQ中间件实现的RPC调用框架 远程调用过程如下 首先:消费者和生产者spring容器初始化的时候,会根据配置的的api在RabbitMQ上建立相应的队列,消费者会监听相关队列 1)生产者(client)调用以本地调用方式调用服务; 2)client 接收到调用后通过Hessian将方法、参数等组装成能够进行网络传输的消息体; 3)client

  • SpringBoot + 前端MVVM 基于Java的微服务全栈快速开发实践。 如今Web开发领域,当有人提到Java时,总会让人觉得臃肿、古老而过时且开发效率没有某些动态语言高效,甚至在此之前还有人高喊“Java 已死!”,但是事实真是如此吗?其实如果你一直关注着Java,那你的感悟会更深,尽管它有很多的缺点和啰嗦,但不可否认,Java依然是工业界中最优秀的语言,而且它一直保持着与时俱进。本项目

  • SpringBoot-Plus 是一个基于SpringBoot 2 的管理后台系统,包含了用户管理,组织机构管理,角色管理,功能点管理,菜单管理,权限分配,数据权限分配,代码生成,子系统生成,文档管理和预览等功能.不同于其他简单的开源后台管理系统,SpringBoot-Plus具备适当的企业应用深度。 系统基于Spring Boot 2技术,前端采用了Layui 2。数据库以MySQL/Oracl

  • �� a simple project for Spring Boot ~ 项目概述 ( �� pause update) �� 一个简单的,基于Spring Boot的好友备忘录小项目,通过本项目可以学习Spring Boot与MyBatis的整合及CURD操作的基本思路,同时也可以帮助你学习Thylemeaf模板引擎使用哟 ! 该项目的代码注释详细,逻辑结构清晰,非常具有参考,学习价值哟 !