Académique Documents
Professionnel Documents
Culture Documents
understand how to work with inheritance, one to many relationship, many to many relationship with hbm file 2. understand how to work with composite primary keys class Employee { @Id int empid; @Id int projectid;
} equivalent syntax in hbm file never use generatedvalue.auto normally u will assign a value to primary key sequence 1st batch will create a sequence/identity at database level we will use this identity/sequence in our code to generate primary key concept of a primary key class ============================ class PrimaryKeyClassname { int empid; int projectid; } why do u need a primary key class?
which interface should this class implement? which methods should this class implemnet? Serializable interface hashcode method equals method tostring method: when a object is printed out Employee e = new Employee(); syso(e);// will print a reference if u want this line to print the value inside the object override tostring method in employee class public String toString(){ syso("this method will be called automatically when syso(e) is encountered ) return empid+" : " +projectid; } caching : storing an object retrieved from the table. subsequent fetch for the same object will result in the obejct being retrieved from the cache and not from the database understnad the behaviour of first level cache thru a program do v know how to reterive an object based on primary key ? session.get(Employee.class,123); EmployeeKeyClass empkeyclassobj= new EmployeeKeyClass (empid,projectid); session.get(Employee.class,empkeyclassobj);
key 1. sql 2. hql : hibernate query language : this works with class names and member variable names and not table names and column names 3. using the hibernate api i.e Criteria interface, Restriction and Projection programmatic configuration instead of maintaining a hibernate.cfg.xml file
3. how to work with a separate class for Primary Key 4. how to fetch records from the table using a. sql b. hibernate query language c. Criteria interface 5. understand first level caching behaviour of hibernate entry in parent class hbm
<set name="transactions" cascade="all" inverse="false" lazy="false" fetch="join"> <key column="FK_ACCOUNTID"/> <one-to-many class="entities.Transaction"/> </set> child class <many-to-one name="account" class="entities.Account" column="FK_ACCOUNTID" />
inverse=true : bidirectional relation if an account number is known to you, can u fetch the transactions of this acccount also, if the transaction id is inown to you, can u determine the account number
eager fetch : if a parent object has related child objects. does fetching a parent record also load the related child records or not if fetch type is eager, then all records are loaded if fetch type is lazy, only parent record is loaded, child records are loaded when an explicit callto the child method is made e.g account.getTransactions()
<set name="owners" table="HIB_PERSON_ACCOUNTS" cascade="all" inverse="true"> <key column="FK_ACCOUNTID"/> <many-to-many class="entities.Person" column="FK_PersonID"/> </set>
person class hbm file many to many syntax <set name="accounts" table="HIB_PERSON_ACCOUNTS" fetch="join"> <key column="FK_PERSONID"/> <many-to-many class="entities.Account" column="FK_ACCOUNTID"/> </set> Serializable interface if an object of a class has to be persisted,it has to implement serializable interface java.io character streams FileReader FileWriter byte streams FileInputStream FileOutputStream
there are some itnerfaces in java which dont have any methods. such itnerfaces are called "marker" interfaces
their purpose is to "mark" a class to be treated specially u did not have to specify serializable for your employee class coz u annotated it with @entity. so hibernate automatically added implements serializable for u hashcode and equals method are related to hibernate caching how does hibernate know that an object is already present in its cache. ?? hibernate refers to the hashcode and equals method of the object equals method : is used to compare the value in 2 objects
String pwd =" abc" if(pwd.equals("abc")) syntax in hbm <composite-id> <key-property name="empno"/> <key-property name="projectId"/> </composite-id> syntax for primary key class <composite-id name="keyEmployee" class="entities.EmployeeKey"> <key-property name="empno"/> <key-property name="projectId"/> </composite-id>
select * from hib_employee order by ename desc select * from hib_employee where salary>4567 select * from hib_employee where salary>4567 and name like 'S%' select sum(salary),avg(sal), count(empid) from emp above can be performed in 3 ways 1. hql : works with classes and member varibale names select keyword is optional in hql session.createQuery
if the query contains all member varibales of the class, return type will be a list<classname> : is used as placeholder to supply values at runtime List<Account> accounts = hqry.list(); if the query contains few column names, return type will be a list<Object[])
2. sql : works with table and column names session.createSQLQuery List<Object[]> records = sqry.list(); records 1st position 1strec obj[] 2nd positon 2nd rec obj[]
every elemnet in the list is an object array List<String> names = new ArrayList<String>(); names.add("abc"); names.add("sdfsdf"); names 1st position abc 2nd positon sdfsdf
3. criteria
session.createCriteria
restrictins are your where clause conditions add restrictions to the criteria
use projections for aggregate methods add projectionlist to the criteria critSummary.setProjection(pl); crit.uniqueResult()--> gives distinct rows
to do fetch all columns, all rows from the table hql : from classname sql : select * from tablename fetch selected columns, selected rows from the table select property1,property2 from classname where condition fetch selected rows from the table from classname where condition
select empname from hib_employee rows returned are of type string List<String> is needed not List<Object> for select empname,gender from hib_employee List<Object> is needed
error msg : No Dialect mapping for JDBC type: 7 solution : download higher version of mysqlconnection.jar hibernate query : select * will not work.only in sql query
"named queries" queries can be written in xml file or via an annotation. how to execute such queries via code syntax of how to write queries in hbm xml file instead of writing sql in java file, v r writing it in hbm xml file @NamedQuery() class Person{
}
<query name="getAccounts">from Account</query> <query name="getAccountsByBalanceRange"> <query-param name="min" type="double"/> <query-param name="max" type="double"/> from Account where balance between :min and :max </query>
in code
Query qry = session.getNamedQuery("querynamespecifiedinhbmfile")
if u open a session and work with an object, this objet is by default cached. if in between u want to pick up the records added by other users, u will have to refresh the session without closing and reopening it. use session.refresh is such scenario
session.refresh(aDB);--> will fire select * from tablename
programmatic configuration of hibernate.cfg.xml file i.e without keeping this file in the project, its properties are specified thru code
cfg.setProperty("hbm2ddl.auto","update"); cfg.setProperty("show_sql","true");
understand the behaviour of first level cache open session fetch a record using primary key observe console. hibernate fires a select statement display its value fetch the same record again . observe console hibernate does not fire a second select since an object by this primary key id is already cached, hibernate will fetch the record from the cache cos session is still open close the session reopen it fetch same record again when u close the session, the cache is also emptied. its state is written to the database another select will be fired
what if the cache object should be alive even after the session is closed. solution : use a second level cache steps 1. add an appropriate jar file.ehcache.jar 2. many predefined implementations of caching exist EHCache is one of them add ehcache.jar to the classpath 3. enable the second level cache which is turned off by default u cannot turn off the first level cache to do this write an entry in hibernate.cfg.xml file
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="cache.use_second_level_cache">true</property> <property name="cache.use_query_cache">true</property> <property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
f. diskPersistent: if true, it uses cache file for maintaining cache g. diskExpiryThreadIntervalSeconds: seconds after which the cache file gets expired if none of the for given time Interval thread accesses -->
in the hbm file specify that this entity needs to be cached another point @Cache(usage=CacheConcurrencyStrategy.READ_ONLY) //above line means cache the account object class Account{
} <cache usage="read-only"/>
currentSession.evict(objectname): forcibly write the state of the object in the cache to the database without closing the session
query cache select * from account1 where accountid=1 results of the query
if u want to refresh a part of the page, use ajax xmlhttprequest create a stored procedure v will call it thru hibernate create identity in mysql v will use it for our primary key generation test on hibernate
from Account --> shortcut for all columns select * from account; * not allowed in hql Query qry = session.createQuery("select employeeid,ename from Account"); List<Account> list = qry.list();
to display dropdown values, determine the values in the controller class, add this list to the model so that it is available in jsp
spring mvc form with different controls spring and sitemesh sitemesh/ tiles are used to achieve a standard look and feel for all pages in the web application internal implemnetation of sitemesh is that of a filter sitemesh-2.4.2.jar sitemesh logic is in filters and custom tags register this filter in web.xml this filter listens to a url pattern html --> controller class html --> filter --> controller class filter will read an xml called decorators.xml mainlayout.jsp : <d:body/> will include the body page at runtime by looking at the return string from the controller's handler method ajax asynchronous javascript and xml traditional web programming involves a reload of the entire page. if u want to refresh a part of the page, use ajax
XMLHttpRequest : object which will send asynchronous request to any server side program
determine whether your browser ajax enabled ? accordingly create an object of xmlhttprequest, open a connection to the server side page and send the request how to call stored procedure thru jdbc and hibernate
//out parameters procedure cannot return any value directly in paramter : value passed to the procedure out parameter : value passed out of the procedure
in out : variable which will contain value passed in as well as the return from the procedure a procedure can have many out parameters create or replace procedure p2(x in number, y in number, result out number) as begin result : = x+y; end; / create or replace procedure p2(x in number, y in number, result out emp %rowtype ) as begin //result : = x+y; select * from emp into result ;
end;
syntax of enum
public enum AccountType { savings("savings"),current("current"); private String type; AccountType(String type){ this.type=type; } //when enum is converted into a column, it is being considered as an int and not string
{ return type; } }
fileupload entry for this class in servletname-servlet.xml <bean id="multipartResolver" class=" org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean> in jsp page <form:input type="file" path="file">
check spring3example project for more info on fileupload joins in hql if u want to fetch data from more than one table using hql refer joins.txt