Jump to content
Sign in to follow this  
poczatkujacy

Hibernate sprawdzanie czy uzytkownik istnieje o takim loginie

Recommended Posts

Witam ,mam następujący problem. Robie aplikacje w Springu i jestem w trakcie tworzenie rejestracji.

Jak sprawdzić czy dany rekord istnieje w bazie danych i by blokowalo mi jego dodanie ? Tak aby metoda nie wiem zwracala np null jestli nie ma takiego uzytkownika albo false.Jeśli chodzi o zapytania to probowalem już kilka rozdzajow nawet z criteriami ale nadal jakiś problem. Porownywalem to co zwraca ta metoda w klasie processform,ale zamiast robic to co chcialem,to dodaje tylko duplikaty do bazy.

 

public class RegisterServiceImpl implements RegisterService {

    @Autowired
    RegisterService dao;

    protected final Logger log = LoggerFactory.getLogger(getClass());

    protected SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public Register getUser(Register register) {
        return (Register)sessionFactory.getCurrentSession().get(Register.class.getName(), register.getUsername());
    }

    public void add(Register user){

               sessionFactory.getCurrentSession().saveOrUpdate(user);
                sessionFactory.getCurrentSession().flush();

    }
    public boolean  exists (Register user) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("select 1 from Register u where u.username =:username");
                    query.setString("username", user.getUsername() );
                return (query.uniqueResult() != null);
    }
@RequestMapping(value="/register.html", method=RequestMethod.POST)
	public String processForm(Model model, @ModelAttribute("register") Register user, BindingResult result,HttpSession session){

		validator.validate(user, result);

		List<FieldError> errors =result.getFieldErrors();
		for (FieldError objectError : errors) {
			System.out.println(objectError.getRejectedValue());
		}

		if(result.hasErrors()){

			return "register";
		}

		if(dao.exists(user)==true)
		{

			return "registeFail";
		}
		else
		{

			dao.add(user);
			return "registerInfo";
		}

	}

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...