Struts2 + Hibernate query result is empty - java

Im trying to collect the result from the query but the list is empty when I check the log in my console. The login action works perfectly but obtain the query result is somewhat not happening. I also used size() to check but it also brings a zero size. What am I missing here
See my dao class:
UserDAO.java
public User userLogin(String email, String password) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User userinfo = new User();
try {
String hql = "select * from user where email =:email and password =:password";
SQLQuery query = session.createSQLQuery(hql);
query.addEntity(User.class);
query.setParameter("email", email);
query.setParameter("password", password);
List rows = query.list();
System.out.println("Total Number Of Records : " + rows.size());
Iterator myItr = rows.iterator();
while (myItr.hasNext()) {
Object ui = (Object) myItr.next();
userinfo = (User) ui;
System.out.println("Username : " + userinfo.getUsername());
}
if (userinfo != null) {
System.out.println("User Retrieved from DB::" + userinfo);
}
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
// close your session
session.close();
}
return userinfo;
}

Try using a Query hibernate and use uniqueResult():
String hql = "from user where email =:email and password =:password";
Query query = session.createQuery(hql);
query.setParameter("email", email);
query.setParameter("password", password);
User userinfo = (User) query.uniqueResult();

Related

Extract and use all values or outputs of searchResultSet for sending an emails

I have this code that searching in the DB and giving me a list of emails like this:
*******#gmail.com
*******#gmail.com
*******#gmail.com
After the searchResultSet I want to use these email Addresses to send an email to them so how I can read them one by one as string.
first class:
public UserDto getEmail() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet searchResultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(
"SELECT EMAIL FROM USER WHERE USER.U_SEQ IN ('1','650')");
searchResultSet = preparedStatement.executeQuery();
return getEmail(searchResultSet);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
private UserDto getEmail(ResultSet searchResultSet) throws SQLException {
List<UserDto > result = new ArrayList<UserDto >();
UserDto userDto = null;
while (searchResultSet.next()) {
userDto = new UserDto ();
userDto .setEmailAddress(searchResultSet.getString(1));
result.add(userDto );
}
return result == null ? null : result.size() == 0 ? null : result.get(0);
}
its working fine.
Second class which is the class that I have to call this searchResultSet to get the emails and use them one by one. Now its working fine but it read and send an email for only the first email or to the value that is in the first row or the searchResultSet. My question is how I can use these rows one by one.
in the second class:
Delegate Delegate = new Delegate();
UserDto userDto = new UserDto();
userDto = delegate.getEmail();
String toEmail = userDto.getEmailAddress();
delegate.sendNotification("****", "****", toEmail, "", "",
"", body);
Here I have to go round to get the values of all rows because only it send for the first email which is the value of first row of the searching result.
Any help!!!
Thank you in advance.
"SELECT EMAIL FROM USER WHERE USER.U_SEQ IN ('1','650')"
This will return you multiple emails, not just one. So you need to attach it to multiple UserDto objects. Not one.
public List<UserDto> getEmail() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet searchResultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(
"SELECT EMAIL FROM USER WHERE USER.U_SEQ IN ('1','650')");
searchResultSet = preparedStatement.executeQuery();
return getEmail(searchResultSet);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
and
private List<UserDto> getEmail(ResultSet searchResultSet) throws SQLException {
List<UserDto> result = new ArrayList<UserDto >();
UserDto userDto = null;
int index = 1;
while (searchResultSet.next()) {
userDto = new UserDto();
userDto .setEmailAddress(searchResultSet.getString(index));
result.add(userDto);
index++;
}
return result;
}
then in delegate,
List<UserDto> users = delegate.getEmail();
loop through users get email and send email

How to update only a certain parameters of the object?

I have a user object in the database, which has the following parameters: username, password, email, admin(boolean).
I want to change only username and that's it. I don't want to touch other fields. The problem with this is that I need to pass a new value for every parameter of the object. My current method, which updates user information looks like this:
String query = "";
query = "UPDATE users SET username=?, password=?, email=?, admin=? where id=?";
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = DriverManager.getConnection(Constant.URL + Constant.DB_NAME, "root", "");
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, user.getUsername() );
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getEmail());
preparedStatement.setBoolean(4, user.isAdmin());
preparedStatement.setShort(5, id);
preparedStatement.execute();
} catch (SQLException e){
throw new RuntimeException(e.getMessage(), e);
} finally {
closeResource(connection, preparedStatement);
}
My update method in the controller:
public static void updateAccountInformation() {
UserDao userDao = new UserDao();
short id = Constant.LOGGED_IN_USER_ID;
System.out.println("Your current account information: ");
System.out.println("Enter new username: ");
String username = sc.nextLine();
System.out.println("Enter new password: ");
String password = sc.nextLine();
System.out.println("Enter new email: ");
String email = sc.nextLine();
System.out.println("Change admin status: ");
boolean admin = sc.nextBoolean();
//parameters i need to pass to the user object
User user = new User();
try {
userDao.updatePersonalInfo(user, id);
System.out.println("User updated successfully!");
} catch (RuntimeException e) {
System.out.println("Something went wrong!");
}
What solution you would suggest in this situation?

How to Update a database row

Basically I want to check if the user exists I want to update with the new object settings. I got stuck on the update clause. How can I do this??
I want to update ALL the data from settings not only user string.
Settings settings = new Settings();
settings.setBaselineImg(baselineImg);
settings.setGitlabUrl(gitlabUrl);
settings.setGitlabToken(gitlabToken);
settings.setProfileProject(profileProject);
settings.setWebCSRProject(webCSRProject);
settings.setWebAdminProject(webAdminProject);
settings.setWebClientProject(webClientProject);
settings.setDockerHostname(dockerHostname);
settings.setDockerIP(dockerIP);
settings.setDockerPort(dockerPort);
settings.setUser(user);
//if settings for this user already exist just Update them
CheckIfSettingsForUserExist(user,settings);
//else Add to database
ManageDatabase.AddToDatabase(settings);
}
private static void CheckIfSettingsForUserExist(String user, Settings settings) {
SessionFactory factory = HibernateUtil.GetSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
try {
String hql = "FROM Settings s WHERE s.user = :user";
Query query = session.createQuery(hql);
query.setParameter("user",user);
//If settings for user already exist
if(query.list().size() > 0)
{
//Update
String hqlUpdate = "UPDATE FROM Settings";
Query queryUpdate = session.createQuery(hqlUpdate);
queryUpdate.setParameter("user", user);
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
Query query = session.createQuery("update settings set user = :user");
query.setParameter("user",user);
int result = query.executeUpdate();
I hope there is going to be a where clause in the query because this update will update all the rows to new user (string value).

Spring - How can I compare values from JSP form to values in db? (Service+DAO)

I'm making a web application (Virtual Clinic)I made DAO and Service layers (I'm beginner at it) for that and it works fine in Controller, but I don't know how can I compare #ModelAttribute("user") User user to values (login, password) which are in db, I want in order to application will redirect to Home.jsp if entered values are in database, if not - then app will redirect to different jsp. Could somebody show me how should I do it properly?
Here is a code:
LoginController:
#RequestMapping(value="/home.html", method = RequestMethod.POST)
public ModelAndView homePagePost(#ModelAttribute("user") User user)
{
setAppContext();
clinicService.checkAuthentication(user);
ModelAndView home = new ModelAndView("Home");
return home;
}
Login.jsp:
<form action="/VirtualClinic/home.html" method="post">
<input type="text" name="login" placeholder="Login"/>
<input type="password" name="password" placeholder="Password"/>
<button>Login</button>
</form>
UserDaoImpl:
public void checkAuthentication(User user) {
String query = "SELECT login, password FROM virtualclinic.user WHERE login=? AND password=?";
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, user.getLogin());
ps.setString(2, user.getPassword());
ResultSet out = ps.executeQuery();
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}// TODO Auto-generated met
}
ClinicServiceImpl:
public void checkAuthentication(User user) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("clinicconfig.xml");
userDAO = ctx.getBean("userDAO", UserDAO.class);
user.setLogin(user.getLogin());
user.setPassword(user.getPassword());
userDAO.checkAuthentication(user);
}
diff the two bean, here is an implementation:
public static List<ChangeItem> getChangeItems(Object oldObj, Object newObj) {
Class cl = oldObj.getClass();
List<ChangeItem> changeItems = new ArrayList<ChangeItem>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(cl, Object.class);
for (PropertyDescriptor propertyDescriptor : beanInfo
.getPropertyDescriptors()) {
String fieldname = propertyDescriptor.getName();
String oldProp = getValue(PropertyUtils.getProperty(oldObj,
fieldname));
String newProp = getValue(PropertyUtils.getProperty(newObj,
fieldname));
if (!oldProp.equals(newProp)) {
ChangeItem changeItem = new ChangeItem();
changeItem.setField(fieldname);
changeItem.setNewValue(newProp);
changeItem.setOldValue(oldProp);
changeItems.add(changeItem);
}
}
} catch (Exception e) {
logger.error("There is error when convert changeset", e);
}
return changeItems;
}
You need to do the below changes to make it work.
1) Add a string return type to method checkAuthentication in the class ClinicServiceImpl.java, to identify whether login is "success" or "failure".
2) Based on this return value in the LoginController.java you can redirect to the appropriate page.
3) In the checkAuthentication method of UserDaoImpl class, you need to check whether any record exist in the DB with the input value username and password.
Code should be as below:
LoginController.java
#RequestMapping(value="/home.html", method = RequestMethod.POST)
public ModelAndView homePagePost(#ModelAttribute("user") User user)
{
setAppContext();
String result = clinicService.checkAuthentication(user);
ModelAndView mav = new ModelAndView();
if("success".equals(result)) {
mav.setViewName("Home");
} else {
mav.setViewName("Login");
}
return mav;
}
ClinicServiceImpl.java:
public String checkAuthentication(User user) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("clinicconfig.xml");
userDAO = ctx.getBean("userDAO", UserDAO.class);
user.setLogin(user.getLogin());
user.setPassword(user.getPassword());
String result = userDAO.checkAuthentication(user);
return result;
}
UserDaoImpl:
public String checkAuthentication(User user) {
String query = "SELECT login, password FROM virtualclinic.user WHERE login=? AND password=?";
String result = null;
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, user.getLogin());
ps.setString(2, user.getPassword());
ResultSet out = ps.executeQuery();
out.last();
int count = out.getRow();
if(count==1) {
result = "success";
} else {
result = "failure";
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}// TODO Auto-generated met
return result;
}

Update data with Struts and Hibernate

i have to update some rows in database using Hibernate and Struts2:
the method DAO where i put the requete is:
public void modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{Query query = session.createQuery("Update Processus set selectionne = '1' where"+cond );
// query.setString("idproc",idprocessus);
// query.setLong("idsi", identifiantsi);
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
In my action class where i call the DAO, i specify the cond:
public String update(){
cond="id_processus="+checked;
procdao.modifier(cond);
return SUCCESS;
}
can u help me it doens't show any error in the console but the row's value don't change!!!!
Following code could be helpful: Processus Table name selectionne and idproc are column name
You need to execute the query
To check the number of updated rows.
public Boolean modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Boolean returnValue = false;
try {
Query query = session.createQuery("Update Processus set selectionne = '1' where idproc=:cond");
query.setString("cond", cond);
int noOfUpdate = query.executeUpdate();
returnValue = (noOfUpdate > 0);
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return returnValue;
}

Categories