开发者社区> 问答> 正文

@OneToOne映射在我的Java Spring项目中不起作用

因此,我整理了我的Spring小型项目,由于某种原因,我注意到@OneToOne注释对我没有起作用,这反过来又导致了另一个模型的问题。

github链接:https : //github.com/eamonmckelvey/sports-app

基本上,我有一个用户模型类,一个团队模型类和一个玩家模型类。我希望只有一个用户能够创建一个团队,而一个团队却要拥有许多玩家。但是,我可以根据需要向用户添加尽可能多的团队,这是错误的。

提供的所有答案都要求我为我的用户类添加一个no arg构造函数和一个构造函数,但是当我这样做时,从类中注册时出现错误。

请帮忙。 1.用户模型

@Entity
 @Data
 @NoArgsConstructor(access= AccessLevel.PRIVATE, force=true)
 @RequiredArgsConstructor
 public class User implements UserDetails {

    @OneToOne(cascade = CascadeType.ALL,mappedBy = "user")
    private Team team;

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    private final String username;
    private final String password;
    //private final String fullname;




    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
    }
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
       }
   }

2.团队模型

@Data
@Entity
 @Table(name="User_Team")

public class Team implements Serializable {

@OneToOne(fetch= FetchType.LAZY)

private User user;

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;

//@NotBlank(message="Team Name is required")
private  String teamName;

//@NotBlank(message="Location is required")
private  String location;

//@NotBlank(message="Nickname required")
private String nickName;

private String yearEstablished;

public Sport sport;

private Divison divison;

3.团队负责人

@Slf4j
@Controller
@SessionAttributes("Team")

public class TeamController {

private TeamRepository teamRepository;

public TeamController(TeamRepository teamRepository) {
    this.teamRepository = teamRepository;
}

 @Autowired
 TeamRepository service;

 @GetMapping("/team")
 public String displayTeam(Model model) {

    model.addAttribute("team", service.findAll());

    return "/team";
   }

    @GetMapping("/addTeam")
    public String showSignUpForm(User user) {
    return "addTeam";
   }

    @PostMapping("/addTeam")
    public String processOrder(@Valid Team team, BindingResult result, SessionStatus 
    sessionStatus,
                           @AuthenticationPrincipal User user, Model model) {
    if (result.hasErrors()) {
        return "addTeam";
    }

    team.setUser(user);
    service.save(team);
    model.addAttribute("team", service.findAll());
    return "team";
}

4.登记表

@Data
public class RegistrationForm {
private String username;
private String password;
//private String fullname;


 public User toUser(PasswordEncoder passwordEncoder) {
    return new User(
            username, passwordEncoder.encode(password));
}
}

5.注册管理员

@Controller
@RequestMapping("/register")
public class RegistrationController {

private UserRepository userRepo;
private PasswordEncoder passwordEncoder;

public RegistrationController( UserRepository userRepo, 
 PasswordEncoder passwordEncoder){
    this.userRepo = userRepo;
    this.passwordEncoder = passwordEncoder;
}

 @GetMapping
 public String registerForm(){
    return "registration";
 }
  @PostMapping
 public String processRegistration(RegistrationForm form){
    userRepo.save(form.toUser(passwordEncoder));
    return "redirect:/login";
}

6.用户详细信息类

@Service
public class UserRepositoryUserDetailsService implements 
UserDetailsService {

private UserRepository userRepo;
@Autowired
public UserRepositoryUserDetailsService(UserRepository userRepo) {
    this.userRepo = userRepo;
}
@Override
public UserDetails loadUserByUsername(String username) throws 
UsernameNotFoundException {
    User user = userRepo.findByUsername(username);

    if (user != null) {
        return user;
    }
    throw new UsernameNotFoundException(
            "User '" + username + "' not found");
}

问题来源:Stack Overflow

展开
收起
montos 2020-03-25 22:49:08 577 0
1 条回答
写回答
取消 提交回答
  • 1.团队负责人

          @GetMapping("/addTeam")
          public String showSignUpForm(SessionStatus sessionStatus,
                                 @AuthenticationPrincipal User user, Model model) 
     {
          //if the user has already the team we should not let them add another 
          // one
          //this is due to having one to one relationship
         long userHasTeamCount = service.countAllByUser(user);
         if (userHasTeamCount > 0) {
    
            return "redirect:team";
    
         }
    
        return "addTeam";
      }
    

    2.团队模式

       @OneToOne(fetch = FetchType.EAGER)
       @JoinColumn(name = "user_id", referencedColumnName = "id")
       private User user;
    

    3.用户模型 在此处删除了OneToOne,因为它不需要

    4.团队回购

    @Repository
    public interface TeamRepository extends JpaRepository<Team, Long> {
    Team findAllById(Long id);
    long countAllByUser(final User user);
    }
    

    回答来源:Stack Overflow

    2020-03-25 22:50:23
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载