1

I am new to Java. I am now using HashMap for the purpose to store data from MySQL database and I will use the JSon POST request to get the input from user and search for the related data in the HashMap and retrieve from the HashMap. I need three inputs from the user but in the HashMap only able to input 1 key. So, I tried the way to input the key as an object but it is not working. Below is my code for storing data from MySQL database.

public class AppDataService {
HashMap<AppDataRequest, AppData> appdatas = new HashMap<AppDataRequest, AppData>();

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://****:3306/****_demo";

static final String USER = "****";
static final String PASS = "****";

public AppDataService(){
    Connection conn = null;
    Statement stat = null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stat = conn.createStatement();
        String sql = "SELECT * FROM testdata";
        ResultSet resu = stat.executeQuery(sql);
        while(resu.next()){
            int id = resu.getInt("app_id");
            String email = resu.getString("email");
            String password = resu.getString("password");
            String status = resu.getString("status");
            String message = resu.getString("message");
            String token = resu.getString("token");
            appdatas.put(new AppDataRequest(id, email, password), new AppData(status, message, token));
        }
        resu.close();
        stat.close();
        conn.close();
    }
    catch(SQLException se){
        se.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally{
        try{
            if(stat!=null){
                stat.close();
            }
        }
        catch (SQLException se2){

        }
        try{
            if(conn!=null){
                conn.close();
            }
        }
        catch(SQLException se3){
            se3.printStackTrace();
        }
    }       
}

    public List<AppData> getAllAppData(){
        return new ArrayList<AppData>(appdatas.values());
    }

    public AppData getAppData(int id){
        return appdatas.get(id);
    }

    public AppData getSAppData(int id, String email, String password){
        return appdatas.get(new AppDataRequest (id, email, password));
    }
}

My JSon POST code

@Path("/appdata")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)

AppDataService ads = new AppDataService();

@POST
@Path("/appdatas")
public AppData getSAppData(AppDataRequest adr){
    return ads.getSAppData(adr.getId(), adr.getEmail(),adr.getPassword());
}

AppData Class

public class AppData {
    public String status;
    public String message;
    public String token;

    public AppData(){

    }   

    public AppData(String status, String message, String token) {
        this.status = status;
        this.message = message;
        this.token = token;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}

AppDataRequest Class

public class AppDataRequest {
    public int id;
    public String email;
    public String password;

    public AppDataRequest(){

    }

    public AppDataRequest(int id, String email, String password) {
        this.id = id;
        this.email = email;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }
}
Reuben Tan
  • 81
  • 8

2 Answers2

0

You can overide hashCode and equals in your class :

@Override
public int hashCode() {
    int hash = 3;
    hash = 83 * hash + this.id;
    hash = 83 * hash + Objects.hashCode(this.email);
    hash = 83 * hash + Objects.hashCode(this.password);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final AppDataRequest other = (AppDataRequest) obj;
    if (this.id != other.id) {
        return false;
    }
    if (!Objects.equals(this.email, other.email)) {
        return false;
    }
    if (!Objects.equals(this.password, other.password)) {
        return false;
    }
    return true;
}

Why you don't make the id like a key if it is unique in your table, and your other information as value of map :

Map<Integer, AppData> appdatas;
appdatas.put(id, new AppData(status, message, token, email, password));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Hi. @YCF_L. Thanks for your reply. I will try on your code of overriding the HashCode and equals. Do we must have the number 83 or any number will do? We try to have id, email, password because email and password also unique as they will only have one entry on our table. – Reuben Tan Apr 07 '17 at 01:02
  • Hi. @YCF_L. I have do some research on the 83. It is the odd prime? – Reuben Tan Apr 07 '17 at 01:06
0

HashMap internally makes use of HashCode and Equals method to insert and retrieve the Object from the collection.

You need to override the equals() and Hashcode() method in Java to use a Custom Object as Key within a HashMap. Also it is preferred to have an Immutable Class as a Key which again you have to consider.

Have a look at below

What issues should be considered when overriding equals and hashCode in Java?

If not you can always use the Standard String/Wrapper Classes as Key as they by default provide the methods and design necessary to use.

As Further Reading look for how HashMap Works and you will understand why.

Hope this helps.

Community
  • 1
  • 1
Nishant
  • 222
  • 6
  • 21
  • Thanks for your reply. I will try on the HashCode and Equals method on my program. I will look on the link as a refer. – Reuben Tan Apr 07 '17 at 00:35