Start from Java 4 -- Collections, Hibernate
07 Apr 2017 | JavaCollections
- from util package, an interface
- Array vs. ArrayList: The issue with arrays is that they are of fixed length so if it is full we cannot add any more elements to it, likewise if there are number of elements gets removed from it the memory consumption would be the same as it doesn’t shrink. On the other ArrayList can dynamically grow and shrink as per the need
- including:
- List
- Set: doesn’t in order, no duplicates
- Map
- Queue: FIFO
- CRUD: create, retrieve, update, delete
- Collection(class):
- sort();
- max();
- min();
- Iterator: thread safe vs. Enumeration: thread not sage
- Iterator: hasNext(); Next();
Iterator iter = arrlist.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } //LinkedList iterator: ListIterator listIt = linkedl.listIterator(); //Iterating the list in forward direction use the same function as above // Iterating the list in backward direction while(listIt.hasPrevious()){ System.out.println(listIt.previous()); } // loops for(ClassName cn : list){...} list.forEach(System.out::println);
- Enumeration: hasMoreElements(); nextElement()
Enumeration<String> e = Collections.enumeration(arrayList); while(e.hasMoreElements()) System.out.println(e.nextElement());
- Iterator: hasNext(); Next();
- Initialize ArrayList:
- Anonymous Inner class method:
ArrayList<String> cities = new ArrayList<String>();
- Collections.ncopis():
ArrayList<Integer> intlist = new ArrayList<Integer>(Collections.nCopies(10, 5));
, we get [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
- Anonymous Inner class method:
- Loop HashMap:
for (Map.Entry me : hmap.entrySet()) {
If we want to use HashSet, we need to override both hashcode() and equal(). These two method are both from java....object class. - hashmap:
- sort by key :
Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
whatever the key is, when you put them to treemap (shift all entries to treemap), your key is automatically sorted. - sort by value : actually is collection, the same as collection, Integer & String can invoke Collections.sort directly; obj – compareTo
- sort by key :
- duplicate:
- add duplicates to set, get false
- hashmap: value equal, fine; key-value all equal, only one entry exists
- Sort in descending order
Collections.sort(arraylist, Collections.reverseOrder());
- If the elements in Collection’s subclass(Set, List…) are objects, we should override compareTo in class first, then sort.
class someClass{ public int compareTo(Object compareobj) { /* For Ascending order*/ return this.prop - compareobj.prop; /* For Descending order return compareobj.prop - this.prop; */ } } public static void main(String args[]){ ArrayList<someClass> arraylist = new ArrayList<someClass>(); ...//add some someClass obj Collections.sort(arraylist); }
s1 = 'a'; s2 = 'h'; s1.compareTo(s2) <=0
- multiple properties:
Collections.sort(arraylist, className.compareOneOfProp); class className{ ... public static Comparator<className> compareOneOfProp = (o1,o2) -> {return o1.OneOfProp - o2.OneOfProp; public static Comparator<className> compareOfAnotherProp = (o1,o2) -> {return o1.AnotherProp - o2.AnotherProp;
- swap
Collections.swap(al, 1, 4);
- Array to ArrayList conversion:
Collections.addAll(emptyArrayList, theArray);
orArrayList<String> citylist= new ArrayList<String>(Arrays.asList(citynames));
- vector. Contructor:
- new Vector(); //capacity:10-20-30
- new Vector(int i); //capacity: 10-20-40…(double)
- new Vector(int i, int i); //capacity: 10-20-40…(double)
- Date & Calendar
Calender cal = Calendar.getInstance(); cal.set(2017,0,1); //month start from 0
- StringTokenizer: like split
- Random: class, function called next.int()
Enum
- An enum is a special type of data type which is basically a collection (set) of constants.
- While defining Enums, the constants should be declared first, prior to any fields or methods.
- When there are fields and methods declared inside Enum, the list of enum constants must end with a semicolon(;).
JDBC
- Connection
- Statement: have some a drawback:
st.executeUpdate("insert into authors (name, age, zipcode) values(" + newName + "', " + newAge + ", '" + newZip + "')");
this can be too complex. - How to improve: PreparedStatement:
- PreparedStatement ps = con.prepareStatement(“…values(?,?,?)”);use Statement, it will be very difficult. so we use preparedStatement, who extends Statement interface
- ps.setString(1, aString);…
- int x = ps.executeUpdate();//insert an entry, x=1??
- what VM argument? min max memory,for heap,start execute, all objects on heap
- oracle: procedure…store block, we can reuse, a lot long business logic, demand of supply,
- 3 procedure: just execute, have argument, can return
- operations in terminal(windows)
- connect system/password–>connected
- create or replace procedure helloproc(x IN number, y IN number, z IN number) as begin (actually have no idea what this procedure is)
z:=x+y; end; / exec helloproc(10,20); //receive return value set SERVEROUTPUT ON declare x1 number; begin helloproc(100,200,x1); dbms_output.put_line(x1); end; / backslash, recall/re-execute previous ...
- maven can only .. open source, so oracle can not use maven. nmp install, get oracle, register local server custom everything
- pom.xml add dependency: oracle
- JDBC drawback: queries, because queries is only for one database. If I change a database, I need to change …
- implement cashing, JDBC api, not able to do that
- class level – mapping to a table
Hibernate ( still have one note to read)
- Java persistent API include:
- JPA
- JTA
- Hibernate
- iBATis
- MyBATis
- model class + test class
- 2 executable file: hibernate.cfg.xml and
.hbm.xml - create hibernate.cfg.xml, copy from document,
- change mapping resource to someclassname.hbm.xml(depends on our project)
- and change password
- set url
- example:(more details about url are in Q&A part)
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">yourpwd</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tables?autoReconnect=true&useSSL=false</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> //important mapping for author <mapping resource="Author.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
- then create someclassname.hbm.xml: change field according to your program: the xml files: class author belong to author123 table
<hibernate-mapping> //the class--yourclassname belongs to table--yourTableName with primary key:id <class name="com.demo.model.yourclassname" table="yourTableName"> <id name="id"> <generator class="increment" /> </id> <property name="name" length="60" /> <property name="age" /> <property name="zipcode" /> </class> </hibernate-mapping>
- create hibernate.cfg.xml, copy from document,
- convert to maven(if it is not)
- add dependencies of hibernate and mysql to pom.xml
- in the test class, configuration, import form …hibernate…
- must t.commit(); or it only saved in JVM.
- steps in terminal in sql:
- use tables
- (optional)source /Users/yourpath/yourTableName.sql;
- select * from yourTableName;
- others: desc table books
- Q & A
- ssl :
- jdbc: jdbc:mysql://localhost:3306/tables?autoReconnect=true&useSSL=false;
- hibernate: jdbc:mysql://localhost:3306/tables?autoReconnect=true&useSSL=false(;)
- ssl :
- Another way to connect database, we do not need any xml configuration file (like someclassname.hbm.xml )for book class, but need annotation: @Entity, @Table(name = “book123”)( class books belongs to table book123, like the xml configuration above)… before class declaration, and in class, we need id(primary key ) and generator setting to AUTO, all from javax.persistance not from hibernate.
- steps in book test class:
- configuration cfg = new AnnotationConfiguration();
- Session ss
- Transition tra
- ss.add
- tra.commit()
- add mapping class = “com.demo.model.Book” in hibernate.cfg.xml
Problem occurred when setting java
- When you want to check what jdks you have, keep in mind that all jdks you have are located in this directory : cd /Library/Java/JavaVirtualMachines/
- what you need to add in ~/.bash_profile
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home PATH=$JAVA_HOME/bin:$PATH CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
- After modify the ~/.bash_profile, you need source it :
source ~/.bash_profile
, so that this file can come into effect.
Comments