Home > front end >  Spring Data Comparison always false
Spring Data Comparison always false

Time:09-08

I'm trying to compare two String values, which on the console are identical, but the returned boolean is always false.

I'm talking about the login() method. I am using PostgreSQL.

This is my Service file:

@Service
public class UserService {

private UserRepository userRepository;

@Autowired
public UserService(UserRepository userRepository) {
    this.userRepository=userRepository;
}


public List<Useraccount> getUsers() {
    List<Useraccount> userList = new ArrayList<>();
    userRepository.findAll().forEach(userList::add);
    return userList;
}

public boolean login(String username, String password) {
    Useraccount user = userRepository.findByUsername(username).orElseThrow(()-> new IllegalStateException("User with Username " username " not found"));
    System.out.println(user.getUsername() user.getPassword() "out");
    System.out.println(username password "in");
        return (user.getUsername()==username);
}

public String userOutput(String username) {
    Useraccount user = userRepository.findByUsername(username).orElseThrow(()-> new IllegalStateException("User with Username " username " not found"));
        return user.getUsername();
}

}

This is my Repository file:

@Repository
public interface UserRepository extends CrudRepository<Useraccount, Long>{

Optional<Useraccount> findByUsername(String username);
}

This is my Controller file:

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

private UserService userService;

@Autowired
public UserController(UserService userService) {
    this.userService=userService;
}

@GetMapping
private List<Useraccount> getUsers(){
    return userService.getUsers();
}

@GetMapping("/login")
public boolean login(@RequestParam(required = true) String username, @RequestParam(required = 
true) String password) {
    return userService.login(username, password);
}

@GetMapping(path="{username}")
public String userOutput(@PathVariable("username") String username) {
    return userService.userOutput(username);
}
}

This is my Console output:

Hibernate:
select
    useraccoun0_.id as id1_1_,
    useraccoun0_.password as password2_1_,
    useraccoun0_.username as username3_1_
from
    useraccount useraccoun0_
where
    useraccoun0_.username=?
DeonisosPasswordout
DeonisosPasswordin

As you can see the in and out is identical, but the boolean always returns false for some reason.

CodePudding user response:

Please use equals method comparison on strings if you re trying to compare the content. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects. So, your login method should return below for accurate results.

return (user.getUsername().equals(username);

  • Related