Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2013
    Posts
    108
    Rep Power
    0

    Default Something wrong somewhere!!!

    I am following the tutorial from the site:
    Hibernate SortedSet Mappings

    It is an example of a sorted set mapping. The example uses a class called MyClass which is basically supposed to sort the certificates in reverse order. But I am getting the same output for natural sorting and MyClass sorting. Something is wrong somewhere.

    Will post the code in the next post.

  2. #2
    Join Date
    Aug 2013
    Posts
    108
    Rep Power
    0

    Default Re: Something wrong somewhere!!!

    Employee Table
    create table EMPLOYEE (
    id INT NOT NULL auto_increment,
    first_name VARCHAR(20) default NULL,
    last_name VARCHAR(20) default NULL,
    salary INT default NULL,
    PRIMARY KEY (id)
    );

    Certificate Table
    create table CERTIFICATE (
    id INT NOT NULL auto_increment,
    certificate_name VARCHAR(30) default NULL,
    employee_id INT default NULL,
    PRIMARY KEY (id)
    );

    Employee.java
    Java Code:
    import java.util.*;
    
    public class Employee {
       private int id;
       private String firstName; 
       private String lastName;   
       private int salary;
       private SortedSet certificates;
    
       public Employee() {}
       public Employee(String fname, String lname, int salary) {
          this.firstName = fname;
          this.lastName = lname;
          this.salary = salary;
       }
       public int getId() {
          return id;
       }
       public void setId( int id ) {
          this.id = id;
       }
       public String getFirstName() {
          return firstName;
       }
       public void setFirstName( String first_name ) {
          this.firstName = first_name;
       }
       public String getLastName() {
          return lastName;
       }
       public void setLastName( String last_name ) {
          this.lastName = last_name;
       }
       public int getSalary() {
          return salary;
       }
       public void setSalary( int salary ) {
          this.salary = salary;
       }
    
       public SortedSet getCertificates() {
          return certificates;
       }
       public void setCertificates( SortedSet certificates ) {
          this.certificates = certificates;
       }
    }
    Certificate.java
    Java Code:
    public class Certificate implements Comparable <Certificate>{
       private int id;
       private String name; 
    
       public Certificate() {}
       public Certificate(String name) {
          this.name = name;
       }
       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 int compareTo(Certificate that){
          final int BEFORE = -1;
          final int AFTER = 1;
    
          if (that == null) {
             return BEFORE;
          }
    
          Comparable thisCertificate = this.getName();
          Comparable thatCertificate = that.getName();
    
          if(thisCertificate == null) {
             return AFTER;
          } else if(thatCertificate == null) {
             return BEFORE;
          } else {
             return thisCertificate.compareTo(thatCertificate);
          }
       }
    }
    hibernate.cfg.xml
    Java Code:
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
     "-//Hibernate/Hibernate Mapping DTD//EN"
     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
    
    <hibernate-mapping>
       <class name="Employee" table="EMPLOYEE">
          <meta attribute="class-description">
             This class contains the employee detail. 
          </meta>
          <id name="id" type="int" column="id">
             <generator class="native"/>
          </id>
          <set name="certificates" cascade="all" sort="MyClass">
             <key column="employee_id"/>
             <one-to-many class="Certificate"/>
          </set>
          <property name="firstName" column="first_name" type="string"/>
          <property name="lastName" column="last_name" type="string"/>
          <property name="salary" column="salary" type="int"/>
       </class>
    
       <class name="Certificate" table="CERTIFICATE">
          <meta attribute="class-description">
             This class contains the certificate records. 
          </meta>
          <id name="id" type="int" column="id">
             <generator class="native"/>
          </id>
          <property name="name" column="certificate_name" type="string"/>
       </class>
    
    </hibernate-mapping>
    MyClass.java
    Java Code:
    import java.util.Comparator;
    
    public class MyClass implements Comparator<Certificate>{
       public int compare(Certificate o1, Certificate o2) {
          final int BEFORE = -1;
          final int AFTER = 1;
    
          /* To reverse the sorting order, multiple by -1 */
          if (o2 == null) {
             return BEFORE * -1;
          }
    
          Comparable thisCertificate = o1.getName();
          Comparable thatCertificate = o2.getName();
    
          if(thisCertificate == null) {
             return AFTER * 1;
          } else if(thatCertificate == null) {
             return BEFORE * -1;
          } else {
             return thisCertificate.compareTo(thatCertificate) * -1;
          }
       }
    }
    ManageEmployee.java
    Java Code:
    import java.util.*;
     
    import org.hibernate.HibernateException; 
    import org.hibernate.Session; 
    import org.hibernate.Transaction;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class ManageEmployee {
       private static SessionFactory factory; 
       public static void main(String[] args) {
          try{
             factory = new Configuration().configure().buildSessionFactory();
          }catch (Throwable ex) { 
             System.err.println("Failed to create sessionFactory object." + ex);
             throw new ExceptionInInitializerError(ex); 
          }
          ManageEmployee ME = new ManageEmployee();
          /* Let us have a set of certificates for the first employee  */
          TreeSet set1 = new TreeSet();
          set1.add(new Certificate("MCA"));
          set1.add(new Certificate("MBA"));
          set1.add(new Certificate("PMP"));
         
          /* Add employee records in the database */
          Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
    
          /* Another set of certificates for the second employee  */
          TreeSet set2 = new TreeSet();
          set2.add(new Certificate("BCA"));
          set2.add(new Certificate("BA"));
    
          /* Add another employee record in the database */
          Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
    
          /* List down all the employees */
          ME.listEmployees();
    
          /* Update employee's salary records */
          ME.updateEmployee(empID1, 5000);
    
          /* Delete an employee from the database */
          ME.deleteEmployee(empID2);
    
          /* List down all the employees */
          ME.listEmployees();
    
       }
    
       /* Method to add an employee record in the database */
       public Integer addEmployee(String fname, String lname, 
                                          int salary, SortedSet cert){
          Session session = factory.openSession();
          Transaction tx = null;
          Integer employeeID = null;
          try{
             tx = session.beginTransaction();
             Employee employee = new Employee(fname, lname, salary);
             employee.setCertificates(cert);
             employeeID = (Integer) session.save(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
          return employeeID;
       }
    
       /* Method to list all the employees detail */
       public void listEmployees( ){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             List employees = session.createQuery("FROM Employee").list(); 
             for (Iterator iterator1 = 
                               employees.iterator(); iterator1.hasNext();){
                Employee employee = (Employee) iterator1.next(); 
                System.out.print("First Name: " + employee.getFirstName()); 
                System.out.print("  Last Name: " + employee.getLastName()); 
                System.out.println("  Salary: " + employee.getSalary());
                SortedSet certificates = employee.getCertificates();
                for (Iterator iterator2 = 
                             certificates.iterator(); iterator2.hasNext();){
                      Certificate certName = (Certificate) iterator2.next(); 
                      System.out.println("Certificate: " + certName.getName()); 
                }
             }
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
       /* Method to update salary for an employee */
       public void updateEmployee(Integer EmployeeID, int salary ){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             Employee employee = 
                        (Employee)session.get(Employee.class, EmployeeID); 
             employee.setSalary( salary );
             session.update(employee);
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
       /* Method to delete an employee from the records */
       public void deleteEmployee(Integer EmployeeID){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             Employee employee = 
                       (Employee)session.get(Employee.class, EmployeeID); 
             session.delete(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
    }
    Expected output based on MyClass sorting:
    PMP
    MCA
    MBA

    Actual Output based on MyClass sorting:
    MBA
    MCA
    PMP
    Last edited by suhaas.mohandos@gmail.com; 08-14-2013 at 11:34 AM.

  3. #3
    kire9dk is offline Member
    Join Date
    Sep 2009
    Posts
    15
    Rep Power
    0

    Default Re: Something wrong somewhere!!!

    According to the documentation provided by
    A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time.
    for more details, check SortedMap (Java Platform SE 6). And read documentation.

Similar Threads

  1. Replies: 4
    Last Post: 06-11-2013, 01:37 AM
  2. what am I doing wrong?
    By snobbysteven in forum New To Java
    Replies: 2
    Last Post: 11-02-2012, 05:08 AM
  3. Replies: 1
    Last Post: 10-01-2012, 02:45 AM
  4. I can't find anything wrong with this but somehow it's wrong.
    By Biscuit Tickler in forum New To Java
    Replies: 2
    Last Post: 09-12-2012, 09:28 PM
  5. What is wrong?
    By phantom06 in forum New To Java
    Replies: 2
    Last Post: 02-02-2011, 06:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •