hibernate/SessionFactory">
8com.mysql.jdbc.Driver
9jdbc:
mysql:
//localhost/test
10username
11pwd
1210
13true
14org.hibernate.dialect.MySQLDialect
15update
16
--Mappingfiles-->
17
18
19
Tokeepthecodesimple,normallyIadddifferentconfigurationsfordifferentclassesinhibernate.
Whatistheneedofdialectinhibernate:
DatabasesimplementsubtledifferencesintheSQLtheyuse.ThingssuchasdatatypesforexamplevaryacrossdatabasesOrdatabasespecificfunctionality–selectingthetopnrowsisdifferentdependingonthedatabase.Thedialectabstractsthissoyoudon’thavetoworryaboutit.Inshortthedialectpropertyinternallycreatesthehighlyoptimizedqueryforunderlyingdatabase.
Herealso,asyoucansee,IhaveincludedfileChatMessage.hbm.xmlfile.
CodeofChatMessage.hbm.xml:
1
xmlversion="1.0"?
>
2
DOCTYPEhibernate-mappingPUBLIC
3"-//Hibernate/HibernateMappingDTD3.0//EN"
4"
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
UIPartoftheapplication:
FortheUI,Ihavewrittenlotsofcssclasses,thisisnotpossibletowritecompletecodehere.Pleasecheckthecodefromdownloadlinkprovidedatthebottomofthearticle.
UIofthechatwindowiscreatedtogivethefeeloftheGmailchatapplicationasshowninbelowimage:
Gmaillikechatwindowwithemoticons
Here,findthejavascriptcode,whichisresponsibletosendtheAJAXrequesttotheservlet,andgettingbacktheresponsecode:
1
2varuEnteredName=prompt("PleaseEnterYourName");
3$("#chat_Header").html(uEnteredName);
4$("#msg").focus();
5
6functionopenEmot()
7{
8var$ele=$("#emoticons");
9varvisibility=$ele.css('display');
10
11if(visibility=='none')
12{
13$ele.show();
14}
15else{
16$ele.hide();
17}
18}
19
20functionsmileyCode(iconCode)
21{
22var$msgEle=$("#msg");
23$msgEle.val($msgEle.val()+iconCode);
24var$ele=$("#emoticons");
25$ele.hide();
26
27$msgEle.focus();
28}
29
30functionsaveChats(){
31varuName=$("#chat_Header").html();
32if(uName==''){
33alert('Pleaseenteryourname');
34returnfalse;
35}
36varmsg=$("#msg").val();
37//varoldMsg=$("#chat-area").html();
38varcolorCode=$('input[name=nameColor]:
checked','#send-message-area')
39.val();
40
41$.ajax({
42type:
"POST",
43data:
"uName="+uName+"&msg="+msg+"&colorCode="
44+colorCode,
45url:
"Chatprocess.do",
46error:
function(xhr,ajaxOptions,thrownError){
47alert(xhr.status);
48alert(thrownError);
49},
50success:
function(data){
51$("#chat-area").html(data);
52$("#ChatAtBigScreen").html(data);
53document.getElementById('chat-area').scrollTop=document.getElementById('chat-area').scrollHeight;
54document.getElementById('ChatAtBigScreen').scrollTop=document.getElementById('ChatAtBigScreen').scrollHeight;
55}
56});
57returnfalse;
58}
59$('#msg').keyup(function(e){
60
61if(e.keyCode==13){
62saveChats();
63$("#msg").val('');
64}
65});
66
Utilityclass,responsibletosavethechatinthedatabaseusinghibernate:
1packagecom.G2.Model;
2
3importjava.util.ArrayList;
4importjava.util.Iterator;
5importjava.util.List;
6
7importorg.hibernate.Query;
8importorg.hibernate.Session;
9importorg.hibernate.SessionFactory;
10importorg.hibernate.Transaction;
11importorg.hibernate.cfg.Configuration;
12
13importcom.G2.pojo.ChatMessage;
14
15publicclassDBManager{
16//ReadHibernate.cfg.xml
17staticConfigurationcf=newConfiguration().configure();
18staticSessionFactoryfactory=cf.buildSessionFactory();
19
20publicstaticvoidsaveChat(ChatMessagechat){
21
22Sessionsession=null;
23try{
24
25session=factory.openSession();
26Transactiontx=session.beginTransaction();
27
28session.save(chat);
29mit();
30
31}catch(Exceptione){
32e.printStackTrace();
33}finally{
34if(session!
=null){
35//Ifacedproblemhere,ifbelowlineisnotwrittenthendataautomaticallygetsdeletedafterinsertion
36session.flush();
37session.close();
38}
39}
40}
41
42publicstaticListgetMessages(){
43ListMessageList=newArrayList();
44Sessionsession=null;
45try{
46session=factory.openSession();
47StringSQL_QUERY="fromChatMessagec";
48Queryquery=session.createQuery(SQL_QUERY);
49Iteratorit=query.iterate();
50while(it.hasNext()){
51ChatMessagec=it.next();
52MessageList.add(c);
53}
54
55}catch(Exceptione){
56e.printStackTrace();
57}finally{
58session.flush();
59session.close();
60}
61
62returnMessageList;
63}
64}
Asshowninabovecode,toworkwithhibernate,ourapplicationwillneedtoreadtheconfigurationfileofhibernatebybelowlineofcode:
1staticConfigurationcf=newConfiguration().configure();
Now,wewillneedtocreatethesessionobjectfromtheSessionFactoryclass:
1staticSessionFactoryfactory=cf.buildSessionFactory();
2Sessionsession=factory.openSession();
Createtheobjectoftransaction:
1Transactiontx=session.beginTransaction();
Tosavetheobjectinthedatabaseusesave()methodofthetransaction.
Togetthelistofchatmessagesfromthedatabase:
1StringSQL_QUERY="fromChatMessagec";
2Queryquery=session.createQuery(SQL_QUERY);
3Iteratorit=query.iterate();
Hereobjectoforg.hibernate.Queryiscreatedandusingmethoditerate(),itgivesalltherecordsfromthedatabaseasaobject.(ThatiswhatORM–ObjectRelationMapping)
ServletCode:
1packagecom.G2.servlets;
2
3importjava.io.IOException;
4importjava.io.PrintWriter;
5importjava.util.HashMap;
6importjava.util.List;
7
8importjavax.servlet.ServletException;
9importjavax.servlet.http.HttpServlet;
10importjavax.servlet.http.HttpServletRequest;
11importjavax.servlet.http.HttpServletResponse;
12
13importcom.G2.Model.DBManager;
14importcom.G2.pojo.ChatMessage;
15
16publicclassChatProcessextendsHttpServlet{
17
18@Override
19prot