你好我一直在努力解决我的错误,因为我是Spring数据的新手,我有一个名为user和role的模型,我想查询具有角色的用户,但角色可以'来自jpa的查询是我的示例代码
用户模块:
@Entity
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
@Column(unique = true, nullable = false)
private String username;
private String password;
private String firstName;
private String lastName;
private String middleName;
@ManyToOne
@JsonBackReference
private Role role;
private Boolean isDisable;
//getter and setters here
}
角色模块:
@Entity
public class Role {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private String roleName;
@ElementCollection(fetch = FetchType.EAGER)
private List<String> privileges;
@OneToMany(mappedBy="role")
@JsonManagedReference
private List<User> users;
//getter and setter
}
角色存储库:
@Repository
public interface UserRepository extends JpaRepository<User,Long>{
User findByUsername(String username);
List<User> findAll();
}
用户服务实施:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private final UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public User findById(Long id) {
return userRepository.findById(id).get();
}
@Override
public User save(User user) {
return userRepository.save(user);
}
}
用户服务:
@Repository
public interface UserService {
User findByUsername(String string);
List<User> findAll();
User findById(Long id);
User save(User user);
}
响应:
{
"id": 4,
"username": "user",
"password": "$2a$10$ZQMkXzXAXyFvvrZ38UnWkuLpe34pM9c2Qnir/4dtZFyxsANYRkMYy",
"firstName": "user-firstname",
"lastName": "user-lastname",
"middleName": "user-middlename",
"disable": false
}
感谢您的帮助