@Entity public class UserDetails { @GenericGenerator(name="sequence-gen",strategy="sequence") @CollectionId(columns={@Column(name="Address_Id")}, generator="sequence-gen", type=@Type(type="long")) private List<Address> arrList = new ArrayList<Address>(); . . . }
Category Archives: Java
Working with Collections in Hibernate
While working with collection if you want the details to be stored in a seperate table using @ElementCollection solves the purpose
UserDetails.java
public class UserDetails { @ElementCollection private List<Address> arrList = new ArrayList<Address>(); }
Address.java
@Embeddable public class Address { private String DoorNo; private String Street; private String Location; private String Pincode; . . . }
createTables.java
public class CreateTables { public static void main(String[] args) { UserDetails objUserDetail1 = new UserDetails(); Address objAddr = new Address(); objAddr.setDoorNo("13"); objAddr.setStreetName("Poes Road"); objAddr.setLocation("Teynampet"); objAddr.setPincode("600018"); Address objAddr2 = new Address(); objAddr2.setDoorNo("256"); objAddr2.setStreetName("Sriman Srinivasan Road"); objAddr2.setLocation("Alwarpet"); objAddr2.setPincode("600018"); objUserDetail1.getArrList().add(objAddr); objUserDetail1.getArrList().add(objAddr2); } }
Giving Names to Joined Tables
- New Table will be created under USER_ADDRESS Name
- joinColumns decides which column should be used for joining two tables
Format for Join Table
@JoinTable(name="JOIN_TABLE_DESIRED_NAME", joinColumns= @JoinColumn(name="userId"))
@JoinTable(name="USER_ADDRESS", joinColumns= @JoinColumn(name="userId")) private Set<Address> addressSet = new HashSet(); . .
Grouping and Sub Grouping Summing
Rows as Displayed in Screen
Rows from Database
Rows grouping Logic
List<RowsBean> outputList = RowsToBeDisplayedList; HashMap<String, ArrayList> superGroupPoints = new HashMap<String, ArrayList>(); HashMap<String, EWMDecimal> subGroupTotalPoints = new HashMap<String, Integer>(); String groupName = null; String prevGroupName = null; String superGroupName = null; String prevSuperGroupName = null; List<Map> subGroupPointsList = new ArrayList(); //Compute grouping totals Iterator itr = cicCarryPointsList.iterator(); while(itr.hasNext()) { RowsBean rowBean = (RowsBean) itr.next(); superGroupName = rowBean.getSuperGroupName(); groupName = rowBean.getGroupName(); //Addition of points summed at Group Level if ((prevGroupName != null && !prevGroupName.equals(groupName)) || (prevSuperGroupName != null && !prevSuperGroupName.equals(superGroupName))) { subGroupPointsList.add(subGroupTotalPoints); subGroupTotalPoints = new HashMap<String, Integer>(); } //Rows at GroupLevel with Sub Groups should be added only when Super Group Changes if((prevSuperGroupName != null && !prevSuperGroupName.equals(superGroupName))) { superGroupPoints.put(prevSuperGroupName, (ArrayList) subGroupPointsList); subGroupPointsList = new ArrayList(); } Integer subGroupValPoints = rowBean.getPoints(); //If InvGrp level Map exists if (subGroupTotalPoints.get(groupName) != null) { Integer currSummedPointsAtGrpLevel = subGroupTotalPoints.get(groupName); currSummedPointsAtGrpLevel = currSummedPointsAtGrpLevel.add(subGroupValPoints); subGroupTotalPoints.put(groupName, currSummedPointsAtGrpLevel); } else { subGroupTotalPoints.put(groupName, subGroupValPoints); } //Incase of last element the loop exits without adding last summed element //To prevent that we add it with out current and prev comparison if(!itr.hasNext()) { subGroupPointsList.add(subGroupTotalPoints); superGroupPoints.put(superGroupName, (ArrayList) subGroupPointsList); } prevSuperGroupName = superGroupName; prevGroupName = groupName; }
Retrieval of Rows for Displaying in Screen
String currentSuperGrouping = ""; String prevSuperGrouping = ""; String currGrouping = ""; String prevGrouping = ""; String Value = ""; for (RowsBean rowBean : outputList) { currentSuperGrouping = rowBean.getSuperGroupName(); currGrouping = rowBean.getGroupName(); //Level 1 - New Super Group Creation //New Super Group should be created when ever prevSuperGrouping and currentSuperGrouping are different if (!currentSuperGrouping.equals(prevSuperGrouping)) { . . Super Group Row Creation HTML Code Goes Here . . . } //Level 2 - Group addition under Super Group //New Group should be created when ever SuperGroup or Group Changes if(!currGrouping.equals(prevGrouping) || !currentSuperGrouping.equals(prevSuperGrouping)) { //Taking Group Level Maps List ArrayList GroupLevelMapList = superGroup.get(rowBean.getGroupName()); Iterator itr = GroupLevelMapList.iterator(); //Taking the Summed up value at Group Level from List while (itr.hasNext()) { Map ii = (Map) itr.next(); Points = ii.get(rowBean.getGroupName()); } . . Group Row Creation HTML Code Goes Here . . . } //Level 3 - Sub Group Rows Addition //Rows will be added if(currentSuperGrouping.equals(rowBean.getGroupName) || currentSuperGrouping.equals(rowBean.getSubGroupName)) { . . Sub Group Row Creation HTML Code Goes Here . . . } prevSuperGrouping = currentSuperGrouping; prevGrouping = currGrouping; }
. as the delimiter with String.split() in java
java.lang.String.split splits on regular expressions, and . in a regular expression means “any character”.
This Wont Work
String[] words = line.split(".");
This Works
String[] words = line.split("\\.");
String Bean in Java
Java Bean Class – EmployeeBean
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class EmployeeBean { private String Name; private int EmpNo; private int Age; private float Weight; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getEmpNo() { return EmpNo; } public void setEmpNo(int empNo) { EmpNo = empNo; } public int getAge() { return Age; } public void setAge(int age) { Age = age; } public float getWeight() { return Weight; } public void setWeight(float weight) { Weight = weight; } public EmployeeStringBean getStringBean() { EmployeeStringBean objEmpBean = new EmployeeStringBean(); objEmpBean.setName(getName() == null?null:getName().toString()); objEmpBean.setEmpNo(Integer.toString(getEmpNo())); objEmpBean.setAge(Integer.toString(getAge())); objEmpBean.setWeight(getWeight()+""); return objEmpBean; } public static List getStringBeanList(List beanList) { List stringBeanList = new ArrayList(); if (beanList != null) { Iterator itr = beanList.iterator(); while (itr.hasNext()) { EmployeeBean bean = (EmployeeBean) itr.next(); stringBeanList.add(bean.getStringBean()); } } return stringBeanList; } }
String Bean Class – EmployeeStringBean
public class EmployeeStringBean { private String Name; private String EmpNo; private String Age; private String Weight; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getEmpNo() { return EmpNo; } public void setEmpNo(String empNo) { EmpNo = empNo; } public String getAge() { return Age; } public void setAge(String age) { Age = age; } public String getWeight() { return Weight; } public void setWeight(String weight) { Weight = weight; } public EmployeeBean getBean() { EmployeeBean objEmployeeBean = new EmployeeBean(); objEmployeeBean.setName(getName()); objEmployeeBean.setEmpNo(Integer.parseInt(getEmpNo())); objEmployeeBean.setAge(Integer.parseInt(getAge())); objEmployeeBean.setWeight(Float.parseFloat((getWeight()))); return objEmployeeBean; } }
Static methods aren’t polymorphic
While developing Java designers made a Mistake by allowing the static methods to get invoked by instance of a class.
someVariable.SomeMethod() I expect it to use the value of someVariable. If SomeMethod() is a static method, that expectation is invalid.
Language spec allows it like VB does and C# doesn’t.
class Base { static void foo() { System.out.println("Base.foo()"); } } class Derived extends Base { static void foo() { System.out.println("Derived.foo()"); } } public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Prints "Base.foo()" b = null; b.foo(); // Still prints "Base.foo()" } }
When you download a file, Response sent back is File
Whenever you submit a form to download a file the response sent back is a file. In this case the setter called after the method which does the download has no effect.
if(form.getDownloadForm != null && form.getDownloadForm.equals("Y")) { downloadForm(form, request); //The Below Setter has No Effect form.setDownloadForm("Y"); }
class RegisterForm() { public String downloadForm; public void setDownloadForm(String p_download) { this.downloadForm= p_download; } public String getDownloadForm() { return downloadForm; } }
The Setter had no effect since the request sent to the downloadForm(form, request); will end up with response of file download and not response which has new values to form set by setter(in our case downloadForm(form, request)) and Page reload.
There are 2 simple fix for this.
Fix 1
One simple fix is to set form hidden property in java script to N after the form get submitted. Note though the form is submitted it is not reloaded with new response since the response sent back is a file.
The Page will be reloaded only when response is sent back to the same URL of browser. Not to the browser as file.
function downloadWFSetup(pWaterfallId) { $('#downloadForm').val('Y'); document.WaterfallTriggerForm.submit(); //This part of code runs even after the form submission since the //response sent is file which does not require page reload $('#downloadForm').val('N'); }
In our case the page is not going to get reloaded so the java script continues its execution even after form submission setting property of downloadForm to N.
Fix 2
The Other way is to send request in Link with downloadForm=Y. In this case there is no need to to reset the form values as we get the values by request.getParameter() Method.
Java == vs equals()
- equals will only compare what it is written to compare, no more, no less.
- if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
- If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
- Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.
With respect to the String class:
The equals() method compares the “value” inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn’t make a difference. Its the “value” (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the “==” operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references “refer to” the same String instance then the result of the boolean expression would be “true”..duh. If, on the other hand, the value of both object references “refer to” different String instances (even though both String instances have identical “values”, that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be “false”.
You will have to override the equals function (along with others) to use this with custom classes.
The equals method compares the objects.
“==” is an operator and “equals” is a method. operators are used for primitive type comparisons and so “==” is used for memory address comparison.”equals” method is used for comparing objects.
The Behavior of equals on class which is final is different.So it is on ENUM.
final class A { // static public static String s; A() { this.s = new String( "aTest" ); } } final class B { private String s; B() { this.s = new String( "aTest" ); } public String getS() { return s; } }
First is the Normal working of equals over a String
public final class MyEqualityTest { public static void main( String args[] ) { String s1 = new String( "Test" ); String s2 = new String( "Test" ); System.out.println( "\n1 - PRIMITIVES "); System.out.println( s1 == s2 ); // false System.out.println( s1.equals( s2 )); // true } }
Now lets see how equals work in final class
A a1 = new A(); A a2 = new A(); System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" ); System.out.println( a1 == a2 ); // false System.out.println( a1.s == a2.s ); // true System.out.println( a1.s.equals( a2.s ) ); // true
In the above you can see that a1.s == a2.s is true.This is because s is static variable and its is possible to have only one instance.(Investigate Further)
Third case is which is well know.
B b1 = new B(); B b2 = new B(); System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" ); System.out.println( b1 == b2 ); // false System.out.println( b1.getS() == b2.getS() ); // false System.out.println( b1.getS().equals( b2.getS() ) ); // true
How to override equals method
Now I have a Person class which has Name and Age as class variables.I want to override equals method so that I can check between 2 People objects.
public class Person { private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Person.class.isAssignableFrom(obj.getClass())) { return false; } final Person other = (Person) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if (this.age != other.age) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + this.age; return hash; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
TestEquals.java
public class TestEquals { public static void main(String[] args) { ArrayList<Person> people = new ArrayList<Person>(); people.add(new Person("Mugil",30)); people.add(new Person("Susan",23)); people.add(new Person("Madhu",32)); people.add(new Person("Monolisa",25)); Person checkPerson = new Person(); for (int i=0;i<people.size()-1;i++) { System.out.println("-- " + checkPerson.getName() + " - VS - " + people.get(i).getName()); boolean check = people.get(i).equals(checkPerson); System.out.println(check); } } }
You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals()
Creating and Running a Jar file in Terminal Java
1.Compile the Files which should be added.
javac Test.java
Incase you are working in eclipse the same thing can be seen under the bin directory in the Navigator tab.you need to navigate to the folder to access the class files.
2.Manifest.txt
Incase if you are going to run the jar file the main class which should be called should be added to JAR file as meta-data through META-DATA/MANIFEST.There should be a Carriage Return Empty line in Manifest.txt to get read properly
Manifest.txt
Main-Class: com.mugil.util.Test
3.Create JAR file using the Below command
jar cfm Test.jar manifest.txt com/mugil/util/*
The Above command should be executed from bin directory in our case
* specifies the list of all files in that folder
4.To Run this JAR file
java -jar Test.jar
When you run the Created Jar file it should be exactly placed in the folder from where the com folder starts.
jar cfm Test.jar manifest.txt com/mugil/util/*
The letters “m” and “f” must appear in the same order that “manifest” and “jarfile” appear.
Creating a MANIFEST File Java
It is a metadata file that contains name-value pairs organized in different sections.
If a JAR file is intended to be used as an executable file, the manifest file specifies the main class of the application. The manifest file is named MANIFEST.MF
Other uses are:
- store hashes of stored files for signature validation
- sealing jar files (i.e. ensure that only classes from this jar file are loaded in the packages defined in this jar file).
- store version/product/producer information to be readable at runtime
The Main class to be called once the JAR is executed is defined as below
If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method
Manifest-Version: 1.0 Main-Class: com.mugil.util.Test