4

In general I want to know how SQL select is implemented in the lower level, it looks like

the algorithm they using is close to O(1)..... in Java you can only achieve this by using

hashmaps, I wander how they did it

EXAMPLE:

If I have a group of student, and group of classes, in order to select any of student belongs to which classes

or any class holds which group of students, I would design a relational database, which 3 tables :

student table, class table, relation table

which should represent a good many-to-many relationship

however if I don't want to use SQL , JDBC, create and design the tables

how can I implement this in pure java

I would like something like

List<Student> getStudentsByClass(String className) 

or

 List<Class> getClassesByStudent(String StudentName)

Ideally I will have a hashMap using unique studentID as key and the actual studentObject as value and another hasMap uing classID as key and classObject as value

then a relation ArrayList holds all the relation objects, inside the relation object you have 2 files, the classID and studentID

the problem is I don't want to loop through the relation ArrayList everytime when I doing a search

I know there is a compare method on object which I can override by that only helps you to sort the obejcts it doesn't help much with select isn't?

there is a link, I understand everything, but not the selecting bit, any one any tips please!

http://www.javaworld.com/javaworld/jw-11-2004/jw-1122-select.html?page=3

5 Answers 5

2

You can iterate over your "table" and check each item for the specified criteria. This will work with O(n) complexity. If you want to make your program faster create kind of indexes using Map (e.g. HashMap or TreeMap) (O(1)) or/and sort data and use binary search (log(n)).

Sign up to request clarification or add additional context in comments.

1 Comment

can you be more specific please? O(n) will work but thats what I am trying to avoid, the key is how to construct the relation collection, should it be a map? a set or ..... a map is nice but you need a unique key...... more importantly what should be the key?
0

Object serialization may work for you here...

public static void testSerialization() {
  String filename = "person.txt";
  StudentDetails s1 = new PersonDetails("hemanth", 10, "Male");
  StudentDetails s2 = new PersonDetails("bob", 12, "Male");
  StudentDetails s3 = new PersonDetails("Richa", 10, "Female");
  List list = new ArrayList();
  list.addAll(Arrays.asList(s1, s2, s3));
  FileOutputStream fos = null;
  ObjectOutputStream out = null;
  try {
    fos = new FileOutputStream(filename);
    out = new ObjectOutputStream(fos);
    out.writeObject(list);
    out.close();
    System.out.println("Object Persisted");
  } catch (IOException ex) {
    ex.printStackTrace();
  }
} 

Of course, reading will be very similar. Sadly, getting "select" queries on this is not trivial. I would suggest looking at the H2 database. It is trivially easy and works very well. Here is a small example that creates the database, a table, inserts stuff and reads it all out again.

public static void h2test() throws SQLException {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:testdb/somedb");

    Connection connection = ds.getConnection();
    PreparedStatement statement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
    System.out.println(statement.execute());

    statement = connection.prepareStatement("INSERT INTO TEST VALUES(10, 'ten')");
    System.out.println(statement.executeUpdate());
    connection.commit();

    statement = connection.prepareStatement("SELECT * FROM TEST");
    ResultSet resultSet = statement.executeQuery();

    while (resultSet.next()) {
        System.out.println(resultSet.getInt(resultSet.findColumn("ID")) + ", " + resultSet.getString(resultSet.findColumn("NAME")));
    }
}

public static void main(String[] args) throws SQLException {
    System.out.println("Hello world");
    h2test();
}

I can really recommend it.

2 Comments

sorry man, no 3rd parth library, even no Serialization, but yes its good idea, but it doesn't help me understand how sql works and how relational database works
Apologies then, but check out H2 for future reference. It's worth to know.
0

You can simply build multiple indexed views to satisfy the queries you want to resolve.

HashMap<String, List<Student>> studentsByClassId;
HashMap<String, List<SchoolClass>> classesByStudentId;

HashMap<String, Student> studentByStudentId;
HashMap<String, SchoolClass> classByClassId;

Maintain these in a single class which acts as your data access layer and provides lookup methods like you suggest. CRUD operations go through that class.

If you later wanted to switch to a database implementation, then the implementation of your data access class changes. But if you've done a reasonable job then it's interface won't.

1 Comment

I agree! its a O(1) and This works, but by giving this I didn't get the job, I wander what is so called better solution..... they said sql jdbc hiberniate isn't the answer.......ahhhhhh
0

I would like to suggest Guava. I don't have the full detail to give you a full example but in guava, you can create Predicates which will act as filters.

I love this tutorial that he did on guava, link to the url is here.

Just to give you an example of a possible use, you can specify a method to return a predicate for you like

public static Predicate<String> isStartsWith(final String input){
    return new Predicate<String>()
    {
        @Override
        public boolean apply( String str )
        {
            if(str.startsWith( input ))
                return true;
            return false;
        }
    };
}

and then call the method as such

filteredList.addAll( Collections2.filter( youList, isStartsWith("thing you want to filter") ) );

1 Comment

thanks but again, no 3rd party library, just pure java please
0

Have you considered using Hibernate? It allows you to use SQL-like queries (HQL) directly on Java objects. It's usually meant to be backed by a "real" database, but you don't have to. In fact, in one of my previous professional experiences, we used it with an in-memory database (HSQLDB) very successfully for that unique reason: being able to do complex queries (including aggregation, joining, etc.) on very large collections of java objects.

3 Comments

a normal people's normal reaction is hibernate, yes! I agree its the best choice, BUT I just want to know is it possible to do this using pure java
If you don't use a database to back your model, you could argue Hibernate is pure java...
sorry pure java means you implement the select algorithm by youself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.