- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我是新来的,希望大家能帮帮我。
我对延迟获取类型有疑问。
我不喜欢只在需要时获取所有关系。当我使用 CommandLineRunner.run
方法时,没关系,它是延迟获取,但是如果我从 RestController
调用该方法,它总是急切但是我不想这样。
我试过:
最后,我将 spring security 与 CustomUserDetailsService 结合使用。当我登录时,它会返回 User 对象。如果 @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 */
Controller :
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;
}
}
登录结果:
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*/
用户DTO:
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*/
}
应用程序.java:
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();
}
}
pom.xml:
...
<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>
应用程序.yml:
spring.datasource:
url: jdbc:mysql://localhost:3306/clms?autoReconnect=true
username: clms
password: clms
testOnBorrow: true
validationQuery: SELECT 1
driverClassName: com.mysql.jdbc.Driver
最佳答案
**对不起,我真的不能写评论,所以我写在这里。
我在这里唯一能看到的是服务类中的@Transactional 注释,并且需要默认传播。
还有一件事,在 Jackson 中 @JsonIgnoreProperties 和 @JsonIgnore 不能一起工作。最好将要忽略的属性放在 @JsonIgnoreProperties(value = {"projects", "reviews"})
希望对您有所帮助。
关于java - spring boot + jpa 延迟获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35482925/
我正在使用一个简单的脚本来延迟加载页面上的所有图像;图像源的路径包含在 data-src 属性中,然后放入 img 标记的实际 src 属性中。几乎大多数(?)延迟加载方法的实现都是如何工作的。 这是
我有一个具有多层 (SKNodes) 背景、游戏层、前景和 HUD 的场景,每个场景中都有多个 SKSpriteNode,用于滚动和您可以收集和点击的对象。 hud 层只有一个 SKSpriteNod
我有一个 Controller 函数来创建一些东西。调用该函数时,将运行 setInterval 来获取项目的状态。 这是服务: (function () { 'use strict';
在我的应用程序中,我播放音频直播,延迟非常重要。我正在使用 AVPlayer,但启动需要 5-6 秒,并且我需要最多 3 秒的延迟。我怎样才能更快地开始播放并减少延迟?设置一个小缓冲区就可以了?如何使
我有一个恼人的问题。我有这个简单的服务器代码(比方说): #!/usr/bin/env python3 import wsgiref.simple_server def my_func(env, st
我是 jquery deferreds 的新手。这里我有一个简单的example 。 谁能告诉我为什么在其他函数完成之前就触发完成函数(“现在是我的时间”)? 这里的人 example还创建一个延迟对
正在放置关闭 之前的标签标记相同的 sa 将它们放在 中部分并指定 defer="defer"属性? 最佳答案 是/否。 是的,因为放置 defer 标签会等到文档加载完毕后再执行。 否,因为放置
我知道Javascript没有delay(500)方法,它会延迟执行500毫秒,所以我一直试图通过使用setTimeout和setInterval来解决这个问题。 for(var i =0; i< 1
我们有一个读写主服务器和复制的从读服务器。在某些网络用例中,数据被发布并立即读取以发送回服务器。立即读取是在读取从属设备上完成的,由于延迟,数据尚未在那里更新。 我知道这可能是复制设置的一个常见问题,
我有以下 dag 设置以从 2015 年开始运行追赶。对于每个执行日期,任务实例在一分钟内完成。但是,第二天的任务仅在 5 分钟窗口内开始。例如。上午 10:00、上午 10:05、上午 10:10
当我在 WatchKit 中推送一个新 Controller 并在新 Controller 的awakeWithContext: 方法中使用 setTitle 时,它需要一秒钟左右来设置标题,直到
我将图像显示为 SVG 文件和文本。 出于某种原因,svg 图像的渲染速度比屏幕的其余部分慢,从而导致延迟,这对用户体验不利。 这种延迟正常吗?我该怎么做才能让整个屏幕同时呈现? Row( ma
我正在考虑在我的应用程序中使用 firebase 动态链接。我需要将唯一标识符从电子邮件生成的链接传递到用户应用程序中。当用户安装了应用程序时,这可以正常工作,但是,我对未安装应用程序的方式有些困惑。
您知道如何使用 JQuery 的延迟方法和一个函数来检测所有已更改的表单并将每个表单作为 Ajax 帖子提交吗? 如果我只列出大量表单提交,我可以得到同样的结果,但如果我使用... $('form.c
我需要一种方法来通过回调获取不同的脚本。这个方法工作正常: fetchScripts:function() { var _this=this; $.when( $.aj
我编写了一个 jquery 脚本,允许我淡入和淡出 div,然后重复。该代码运行良好。但是,当我尝试添加延迟(我希望 div 在淡出之前保持几秒钟)时,它无法正常工作。我尝试在代码中的几个地方添加延迟
我正在努力在延迟、带宽和吞吐量之间划清界限。 有人可以用简单的术语和简单的例子来解释我吗? 最佳答案 水比喻: 延迟 是穿过管子所需的时间。 带宽是管有多宽。 水流量为吞吐量 车辆类比: 从源到目的地
我有一个 CRM 系统,当添加联系人时,我想将他们添加到会计系统中。 我在 CRM 系统中设置了一个 Webhook,将联系人传递给 Azure 函数。 Azure 函数连接到会计系统 API 并在那
我有一个 Android AudioTrack,例如: private AudioTrack mAudioTrack; int min = AudioTrack.getMinBufferSize(sa
我正在 React 中开发一个 TODO 应用程序,并尝试构建将删除选中项目延迟 X 秒的功能,并且如果在这段时间内未选中该框,它将不会被删除。 我遇到的主要问题是当用户在同一 X 秒内检查、取消检查
我是一名优秀的程序员,十分优秀!