I am programming an IHM for sign up the users, I need to check if this user is already in database(mysql), checking by his email . can you help me please.
I can save my user now but how to check if this user by his email
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I have a table user in my database.
thanks for your help in advance
I would use NamedQuery for this. Define named query in your User entity like this:
...
#NamedQueries({
#NamedQuery(name = "User.findByEmail",
query = "SELECT u FROM User u WHERE u.email = :email")})
#ManagedBean(name="user")
public class User {
...
And then add method like this to your DAO
public List<User> getUsersByEmail(String email){
openSession();
Session session;
Query query = session.getNamedQuery("User.findByEmail");
query.setString("email", email);
Lis<Users> users = query.list();
closeSession();
return users;
}
This method is little bit more generic you can make it more specific returning user count only.
Related
I am very new to Spring Boot. This is what I want to do: The user's email is test#example.com. That user already exists in my database, but I would like to know if their verificationCode is 123.
Entity:
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email;
private String password;
private String verificationCode;
#Column(name = "verified", columnDefinition = "default false")
private boolean verified = false;
#CreationTimestamp
private Date registrationDate;
protected Users() {}
public Users(String email, String password, String verificationCode) {
this.email = email;
this.password = password;
this.verificationCode = verificationCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
So with userRepository.findByEmail("test#example.com") I am getting the correct user, but how do I check their verification code?
if you're using userRepository.findByEmail("test#example.com"), just take the verification code from entity.
private static final String CODE = "123";
final User user = userRepository.findByEmail("test#example.com");
if (CODE.equals(user.getVerificationCode())) {
// do something
}
Another option to have it within query.
userRepository.findByEmailAndVerificationCode("test#example.com", CODE);
Or you can have something similar as Philipp wrote, but I would not get whole entity just find out if it exist. So solution would be
if (userRepository.existsByCode(CODE)) {
// do something
}
You search for something like that:
public void checkVerificationCode(final String verificationCode) {
final User user = userRepository.findByEmail("test#example.com");
if (!user.getVerificationCode(verificationCode)) {
throw new VerificationCodeException("Incorrect verification code.");
}
}
Main method
EntityManagerFactory emf=Persistence.createEntityManagerFactory("manager1");
EntityManager em1=emf.createEntityManager();
EntityTransaction entityTransaction=em1.getTransaction();
entityTransaction.begin();
Person persons=JPA_basic_Example.setPerson();//fills all the fields of person
Credential cred=JPA_basic_Example.setCredential();//fills all fields of credentials
System.out.println("check1");
cred.setPerson(persons);
persons.setCredential(cred);
em1.persist(cred);
entityTransaction.commit();
em1.close();
emf.close();
Java Bean Credential oneToone Bidirectional with Person
public class Credential {
#Id
#Column(name ="credentialid")
private int credential_id;
private String UserName;
private String Password;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="Personid")
private Person person;
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getCredential_id() {
return credential_id;
}
public void setCredential_id(int credential_id) {
this.credential_id = credential_id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Java Bean Person
#Entity
public class Person {
#Id
#Column(name ="Personid")
private int person_id;
//#Basic(optional = false)
//#Column(name ="Name", unique = true)
private String name;
#ElementCollection
#CollectionTable
List<String> contact=new ArrayList<String>();
private Address address=new Address();
#OneToOne(mappedBy = "person", orphanRemoval = true )
Credential credential ;
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public List<String> getContact() {
return contact;
}
public void setContact(List<String> contact) {
this.contact = contact;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerson_id() {
return person_id;
}
public void setPerson_id(int person_id) {
this.person_id = person_id;
}
}
Output Console
Hibernate:
insert
into
Person
(area, city, pincode, state, name, Personid)
values
(?, ?, ?, ?, ?, ?)
AFter this code stuck and nit moving forward nor showing any exceptions or errors
I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
I need to verify the email of the new user who would like to sign up in my application web. if the email is already in my database (mysql) so must don't accept this sign up and said said to him like: "your email already used".
Now I can save users in my database, but how to check them by his email for not repeat the inscription in my application web.
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I created a table "user" in my database.
Maybe there is an annotation which can help us to specify the email property as an unique one or something else.
What you can do is create a unique key on your email column in your table. After that, decorate your field using #Column(unique=true), that will indicate to Hibernate that this field has a unique key.
Also, be careful with your annotations. This is unrelated to your problem, but #ManagedBean marks the class as a bean able to interact with the view in JSF. Probably you want/need to use #Entity instead.
I have a problem with Hibernate to make login process. All codes are perfectly correct in terms of syntax. NetBeans tell me that my code have no problem. However, when I run the web, and I test the login process, it doesn't reacting and the address is stucked on the doLogin.
All classes have been mapped correctly.
This is my problem: when I try to retrieve data, my code is stucked on a line.
on doLogin servlet (I use the template provided by NetBeans and just filling in my code on the try. Here's in brief:
Connect con = new Connect(); //my code is stucked on this line.
//I've done testing where's the cause of the stuck, and this line is the cause.
List logger = con.getLogin(username, password);
and to make it clear:
Connect.java
public class Connect {
Session sesi;
public Connect() {
sesi = HibernateUtil.getSessionFactory().openSession();
}
public List getLogin(String username, String password){
return sesi.createQuery("from MsUser WHERE username = '"+username+"' and password = '"+password+"'").list();
}
}
and since that query is HQL, here is the MsUser class:
public class MsUser {
public MsUser() {
}
private int userID;
private String username;
private String firstname;
private String lastname;
private String email;
private String password;
private String gender;
private String address;
private String phone;
private String photo;
public MsUser(int userID, String username, String firstname, String lastname, String email, String password, String gender, String address, String phone, String photo) {
this.userID = userID;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.password = password;
this.gender = gender;
this.address = address;
this.phone = phone;
this.photo = photo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
please help. But I suspect on Connect's constructor as the main cause. Anybody can suggest or fix or tell me what causing me this.
appendix:
HibernateUtil.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* #author Ginanjar
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
You can try following code in your hibernateUtil.java file:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
String query = "select reg.username,reg.password from MsUser as reg where reg.username='" + username + "' and reg.password='" + password + "'";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) { it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}