RSS
 

JPQL in JPA

25 Dec

Query query=em.createQuery(”select k from Candidate k”);
The above JPQL query is similar to writing the following query in SQL-
select * from candidate;

Transform the following SQL queries into JPQL query:
Given that Employee entity is mapped to empl table and has empId,empName as two attributes.
1. select * from empl;
2. select empid from employee;
3. select empid,empname from employee;

Answers:
1. select e from Employee e
2. select e.empId from Employee e
3. select e.empId,e.empName from Employee e

Note: The queries of JPQL are case sensitive (only in terms of variables and Entity names). If here empid is given instead of empId, it would result into exception.
For the below examples, Candidate is the entity class, mapped to candidate table and having 4 instance variables as candidateId, name, marks and DOB

Example 1-
Query query=em.createQuery(”select k from Candidate k”);

Output:
1 John 56 12-JAN-11
3 Monica 87 23-OCT-88
4 Rachel 22 01-JUN-09
2 Jack 90 01-SEP-11

The above JPQL query is similar to writing the following query in SQL-
select * from candidate;

Each row above represents a candidate class object. So we can write the following:
Candidate cd=(Candidate)rs.get(i); // => get the ith row
Here ‘i’ can take values from 0 to the size of list-1
Note: If no rows are present, no exception is thrown (size will come out to be 0)

Example 2-
Query query=em.createQuery(”select k.name from Candidate k”);
Output:
John
Monica
Rachel
Jack

The above JPQL query is similar to writing the following query in SQL-
select name from candidate;
Each row above represents a String class object. So we can write the following:
String s= (String)rs.get(i); // Line 1
Here ‘i’ can take values from 0 to the size of list-1
Note: If no rows are present, no exception is thrown (size will come out to be 0)
If here, Line 1 is replaced with Candidate cd=(Candidate)rs.get(i);
it would throw ClassCastException(Since now the query doesn’t return candidate object, but only String object)

Example 3-
Query query=em.createQuery(”select k.name,k.candidateId from Candidate k”);

John 1
Monica 3
Rachel 4
Jack 2

The above JPQL query is similar to writing the following query in SQL-
select name,candidateid from candidate;

Each row above is a combination of 2 objects, String and Integer. So if we get each row, it would not return a single type of object => “String s= (String)rs.get(i);” cannot be done .
But Object can handle any type of objects. Here we use object array (since each row has 2 different objects).
Object [] obj = (Object[])rs.get(i); // Line 1
Here ‘i’ can take values from 0 to the size of list-1
Note: If no rows are present, no exception is thrown (size will come out to be 0)

We can write-
Object[] obj = (Object[])get(i);
String name=(String)obj[0];
Integer id= (Integer)obj[1];

 
Comments Off

Posted in Tech

 

Defining sequences in JPA

23 Dec

After registering for an account in bank, user is given an id. This id is autogenerated. Let us see how we do this through Java Persistence API.

Method 1 : Default generated value strategy

Employee class is created as shown below-

@Table(name=”empl”)
@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int empId;
private String name;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

As is evident, the table in database(backend) is named ‘empl’ and so is mapped with @Table annotation and the id is ‘empId’. For this type of generation, we need to use @GeneratedValue annotation where strategy defines how the value should be generated by JPA. There are four types :
a)strategy=GenerationType.SEQUENCE : should be generated sequentially starting with 1
b)strategy=GenerationType.IDENTITY : should be assigned randomly, through identity column in database(column having all unique values)
c)strategy=GenerationType.TABLE : should be assigned randomly by picking from a primary key column of any table in database
d)strategy=GenerationType.AUTO : JPA can generate using any of the above three strategies

So, the starter class might look as below:

public class EmployeeService {

public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(”My”);
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
Employee employee = new Employee();
employee.setName(”Apr”);
em.persist(employee);
em.getTransaction().commit();
System.out.println(”Persisted into database”);
System.out.println(employee.getEmpId());
}
}

On executing,
1st time Output:
Persisted into database
0

2nd time Output:
Persisted into database
1

Method 2 : User defined sequence
Employee class is changed as shown below-

@Table(name=”empl”)
@Entity
public class Employee {
@Id
@SequenceGenerator(name=”seq_empNo”,sequenceName=”db_seq1″,initialValue=1,allocationSize=10)
@GeneratedValue(strategy=GenerationType.SEQUENCE),generator=”seq_empNo”)
private int empId;
private String name;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

@SequenceGenerator is used to create user defined sequence in backend . So here, after the program is run once, a sequence in database will be created with name ‘db_seq1′ , initial value 1 and increment by 10.
@GeneratedValue generates the values based on the strategy type and sequence generator

The starter class remains same as above EmployeeService.
On executing,
1st time Output:
Persisted into database
1

2nd time Output:
Persisted into database
11

Note: If the JPA provider is toplink, then SEQUENCE doesn’t work as it should. It’ll generate random values for both the methods.

 
Comments Off

Posted in Tech

 

Get a Life!

03 Dec

jenkinsPersonOne : Hey dude, what plans for weekend? Lets go partying!
PersonTwo : Nah! I don’t fancy parties
PersonOne : What?? Get A Life, Man!

PersonOne : Hey,What are you upto today?Let’s go for a movie
PersonTwo : I’m tired of work
PersonOne : Come on, Get A Life!

I hate it when people pretend to be cool and famous.They try to rob you blind with their fake pretensions. The definition of cool has changed to being able to spend money on showy things. If you have money you can spend blindly, you’re cool; you have car, you’re cool; you drink, you’re cool; you live abroad, you’re cool; you smoke, you’re cool! For god’s sake, these are the ones who need to get a life! They are wasting this one, anyways. They fall in the category of frustrated people, who have nothing to do or always pretend to be busy(with-”Nothing“). Some of them drink and smoke. These two activities are a status symbol, a sign of maturity and sophistication. Well, LOL!

In summary, to ‘Get a life!’ is no simple matter. The alternative, however, is to waste the precious opportunity we have to make the most of the one that the universe has given us.

 
 

Do more with less – ‘Ways to save time’

08 Oct

time backAre you time pressed?
Do you often feel that there should be more that 24 hours a day?
Do people around you complain that you are always busy or involved in some or the other work?

If the answer to these questions is “YES”, then surely you need to devise some ways to better manage your time.

I too, have been a dupe and very much hard bound with time. In the past, I had been cutting down on my sleeping hours to meet all the personal and professional engagements. Lately, I have realised that I need to better manage my time and prioritise things in order to keep a healthy balance between personal and professional life.

All over this time, I have been pondering to figure out ways to shave minutes of certain activities and thus, here is the list of time saving tips which I have been able to jot down.

1. Do all means do none – There are people who want to do everything, accomplish each task undertaken, meet all the expectations, experience everything. Personally, I feel this is not possible. You need to let forgo certain things and focus on the prime ones only in order to best utilise your time. The key is to ‘PRIORITISE’. If you try to do justice to each and every task then surely you will get time pressed and eventually there would be things which would suffer.

2. Be professional towards your personal life – A true saying indeed! One needs to be very much professional towards ones personal life also and not let your professional life eat up your personal space.

3. Plan your day – To best utilize your time, make a list of activities you plan to undertake during the day. Some people like to make plans on their PDAs, Personal Calendars, Tablets, etc; some prefer it to write them down whereas some only run through those in their brain. Whatever technique you choose, try and enlist all the important tasks that you need to finish before you start your day.

4. Check your phone while in queues – Waiting in line is a waste of time, so use this time to check your email, respond to text messages or participate on social media.

5. Automate your monthly expenses – Stop paying bills through the conventional system of going to the offices, recharge shops or collection centres and switch to paying your expenses online. If you are already doing that, the next step is to automate your payments and set a time once a month to review all your monthly payments.

6. Maximize your commute times – Read a book, listen to audio-books, call people, email, catch up on sleep, talk to strangers to gain knowledge or get other work done.

7. Stop watching TV – Cut back on watching television and watch only specific shows which interest you the most. The best alternative is to catch those shows online, where commercials could be fast forwarded and you can watch them at your own pace and time.

8. Learn keyboard shortcuts – Using the mouse can be slow for certain tasks which oftentimes can be done faster by keyboard shortcuts. Learn a couple keyboard shortcuts of your frequently used programs like your web-browser, word processor, calculator, notepad, etc.

9. Stick to 3 tasks – If you only had time for 3 tasks each day to complete to make your day worthwhile, what would they be? Answering this question forces you to prioritize so you spend time on important things and avoid working on things that have little importance.

10. Call people – Sometimes calling is much faster than sending text or emails. What can be said in less than a minute usually takes you a couple of minutes drafting and framing in the right context.

11. Batch your activities – Putting activities that are similar in nature allows you to process them faster and in one batch. For example, if you need to call or text people, do that in one batch instead of spreading it throughout the day.

12. Tame your online usage – Online activities can be a big productivity killer. Firstly, one needs to better manage his mailbox. For that, unsubscribe from newsletters you don’t read, make categories for each mail, and sought mails as soon as you read them. For other online activities like social media, set each session to a limit of 25 minutes.

13. Breaks are important – Working on a stretch leads to drop in productivity and in turn leads to wastage of time. Take a few breaks in between and use those breaks to call friends, send sms, etc.

14. Try a different route – We are creatures of habit and we like to stick to the path of least resistance. Once we have commuted to work on a particular route, we stick to that route no matter how bad the traffic is. Have you ever considered planning a new (and more efficient) route to work? This applies not only for commuting but for other tasks as well. One needs to experiment to find the best optimal way to do any task. Once done, use it to save time in future.

15. Touch it once – Whenever you get something in front of you, decide right away what to do with it. Don’t let it sit around for you to decide another time what to do. Either plan, do it, delegate or delete.

16. Clean your desk at the end of the day & set up your things before beginning a task – Before you stop working for the day, clean your desk. This makes it easy for you to get started the next time you start working. Also, before undertaking any task, set up the ambience and grab hold of all the required things.

17. Improve your typing speed – Considering you spend a lot of time writing emails and documents, it’s worthwhile learning how to type faster. This will add extra minutes to your day.

18. Eat your frog – As you prioritise tasks for each day, also take a note of the most difficult task. Try to finish up that task as soon as possible. Once you eat your frog, other tasks would seem less complex and it would also give you a positive boost of energy to finish up other things quickly.

TimemanagementCurrently, I am also trying to imbibe all of these points in my daily routine and would eventually add a few more as I discover them.

But here I would like to pin down another point viz. we need to realise the fact that there are people who are workaholic and like to be engaged in work all round the clock. For them, it’s the way of their life. Even if they squeeze out time using these techniques, they would eventually find some or the other task to get involved with. So on one hand time management would prove to be a boon for them but on the other, they would get even more loaded with work.

Anyhow, to conclude Time Management is surely a way to live an organised life.

 
Comments Off

Posted in Creative Pen

 

Why is everyone around me getting married???

25 Sep

Have you got to a point where you feel all of your friends are getting married around you?
I go to my workplace and most of my collegues plus friends are sending mails regarding :
1. engagement
2. getting married
3. planning to get married
Quite frankly, my first reaction was to get married!!! Well, somebody’s got it right: The first reaction to truth is hatred.

I’ve read this somewhere: “You should get married when you have found the right person and you’re really sure that this is someone you want to spend the rest of your life with“. Sure. But as good as it sounds, there is a lot more to it. (Before I get started with it, don’t get me wrong. Above all things I believe in love and trust me on this, it has changed my world )! For a moment, just imagine this age to be 20. At 20, we have not seen the ‘real’ life. And this real life is “No Cool”. We do not get up early to go to some “job” which we might not even fancy doing. We do not come home all weared out. We do not have peer pressure or work load. And there is so much more!
3736903415_df0e51246aWe need to come out of our comfort closet and take a moment to think, if you have never faced everyday challenges of life and have not experienced what is takes “to be” in this world, how do you plan to take care of not just your own self, but “two of you” so early! We people are responsible for our own life. So there is a clause added to the above quote: Being practical.
The fact still remains that in our so called Indian society, the social pressure is much more on the females. According to our parents, there is an age limit after which no one will ever marry us. And yes, you guessed it right, its 22, just after you have become educated. No one realises that we have just got  a “degree” to get a job not to get all “settled”. I mean I completely second the idea that we should get married, but when are we going to understand that marraige should not be out of convenience but more of “growing old with and living together”. Even if you are in love with someone who’s perfect for you, it’s important to first get to where you want to be. In the age where so many marriages are ending up in divorces, shouldn’t we take our time and make sure we aren’t rushing into anything. Its crucial to make yourself a better person and try new things and experience life before you settle down, you will regret it later if you don’t! If not for yourself, let the other person make his space. Planning always pays off. So while I’m still taking time, I’m glad its happening this way.

Cheers to love and life :)

 
 

Let the Race Begin

01 Sep

It has been a remarkable season for Sebastian Vettel in 2011 FIA Formula One World Championship,  where he has won 7 times uptil now.  RBR-Renault stands first scoring 426 points followed by McLaren-Mercedes . Amongst all the races this year,  Canadian Grand Prix stole the show.

images

The  Indian Grand Prix is scheduled to take place on 30/10/2011 at the Buddh International Circuit in Greater Noida, Uttar Pradesh. There was some controversy by the farmers over the land acquired for preparing track for the upcoming Jaypee’s Formula One race in India. Indian construction company Jaiprakash Associates has constructed the track that was designed by F1 circuit designer Hermann Tilke. The circuit is 5.137 km long and the expected F1 car lap time is 1 minute 17 seconds. The track’s combination of 16 corners, high-speed straights and dramatic changes in elevation will make the race all the more interesting. In addition to F1, the track is also expected to host other top-level international motorsports events from 2012 onwards.

JPSI(Jaypee Sports International Ltd.) is facilitating Grand Prix bus services running from number of pick-up points in Delhi, NOIDA and Gurgaon directly to Buddh International Circuit. Also there are offers on purchase of 2 or more tickets.

Economically, India joining the F1 calendar seems to bring boon to the tourism industry here; thus lifting up country’s profile. The tickets range from INR 2500 – 35000 based on the four zones around the track. The Rs 2,500 tickets are for the natural stand and have been sold out already. Bharti Airtel joined hands with the Formula One (F1) Group Companies to become title sponsor  for the first five years of Indian grand Prix (F1 2011 to F1 2015). Along with Airtel, sponsors of Indian Grand Prix will include F1 Force India team  sponsors (UB Group Brands including Royal Challenge, Kingfisher, etc.) Reebok, Tata, Wrigley etc.

Starting on Fri 28 October 2011, Practice 1 will be from 10:00am – 11:30am and Practice 2 from 2:00pm – 3:30pm; then on Sat 29 October 2011 Practice 3 will start from 11:00am – 12:00 noon and Qualifying at  2:00pm. Finally the race will kickoff on Sun 30 October 2011 at 3:00pm.

Lets wait and see how India welcomes F1.

 

Fringe-The unconventional

07 Aug

Amongst the various meanings of the word “fringe”, one wonders which one could fit in for the exclusive science fiction television series. Exceptionally well directed and presented, this series falls under the genre of science fiction, thriller and horror. The concept of parallel universe is the main theme where the FBI is set to find the reasons for “the pattern”. Agent Olivia Dunham proves to be outstanding in unwinding the hidden mysteries along with the  Bishops. It becomes all the more interesting with Doctor Walter Bishop’s notable character. You might have observed ordinary looking images displayed at the end of each act, just before commercial breaks.

Imagine The Impossibilities – http://www.imaginetheimpossibilities.com is a website created to tie in with Fringe.

To know about the significance of each of these symbols- http://www.fringepedia.net/wiki/Fringe_Symbols

Fringe has completed it’s third season. Following are the torrent links for the same:

Season 1 Fringe_-_Season_1.torrent
Season 2 Fringe Season 2 Complete HDTV[AGENT][1337x.org].torrent
Season 3 Fringe.S03.HDTV.H264.6373673.TPB.torrent


I have a penchant for non-thriller series and seasons, but I like fringe.

Paradoxes!!!

 

From 80286 to the Cloud – “a small step for man, a giant leap for mankind”

04 Aug

cloudcomputingThere’s no network….All mobile phone networks are down….Internet is also not working….No means to connect to the outside world.

The universe has been unplugged!!!

WHAAAAAAAATTTTT?????????

Nooooooooooo, it can’t be true…it has to be a nightmare…..it has to be, has to be one !!!

Jas: Heyyyy, what are you blabbering??

Me: [Still in a state of shock] oh, so it was a dream indeed. Thank God …woosh.

Jas: What did you saw? Why are you so tensed? Here take some water.

Me: [After having a sip] I just had a nightmare. I saw that the world has come to an end. There are no means to communicate, everything has got jammed. It made me realise the importance of being ‘connected’. Imagine a day without technology; don’t know how are great grand-fathers and grand-fathers used to live!!

Jas: True brother, very true.

Me: Even after today’s MIS# lecture in college, I had realised the same. All thanks to web based enterprise systems which empowers the net

Jas: Hey, Hey… Stop…Is it some new application on Facebook or have Google launched a new product?

Me: No no no….All you know about computers is Google and Facebook. Wait; let me explain you in detail starting from the very basics of Systems Architecture.

Jas: Go on, I am all ears.

Me: To begin with, Systems Architecture is all about grouping of data and processes along with applications and the ways how they are processed. Systems Architecture can be of different types like: 1-tier, 2-tier or multi-tier where data and applications are separated in different fashions.

Jas: Hmmm….Sounds interesting, tell me more…

Me: Ok, So basically data signifies the information which is to be processed and applications tell how the data would be processed. The main principle to note is that both data and applications should be logically separate. In single-tier architecture, both these data and applications reside on the same machine. Like do you remember the time when my dad bought home the first PC? It was an x80-286 machine which had limited capacity and processing power. Although, it was a standalone machine without any internet connection; and data & applications resided on it but they were separated from each other logically. For e.g. you can create a word document and take it anywhere – that is your data whereas the MS-Word or Open-office is the application which would process it.

Jas: Hmmmm….so what about the other tiers that you mentioned?

Me:  ok, so two tier architecture is also known as client server architecture. In this kind of architecture, data lies on a different machine known as the server whereas the applications are installed to access the data on each client machine. The server stores the data in a database and the client machines only have the presentation & GUI.

Jas:  So how do these clients access this data?

Me: The clients can be connected to the server through a LAN i.e. a local area network, like the one in your dad’s office or they could make use of WAN or the internet if they are separated by a huge distance.

Jas: Fair enough, so this 2 tier architecture seems to be powerful enough, then why do you need subsequent systems architectures like 3-tier or multi-tier?

Me: Due to the presence of applications on each client system, it was a problem to update the application software and to maintain consistency of software version being used, so this gave birth to 3-tier architecture where the business logic or the application is also separated from the client machine. The clients now have only the user interface where data can be seen like in case of a browser e.g. Mozilla Firefox. This also reduces the amount of data that needs to be transferred over the network. This is actually the underlying technology behind the websites and the web-pages that you visit on the internet.

Jas: Ahhhaa….now I get it. Tell me more what did you learn in your MIS class @ VGSOM*??

Me:  Someone is really enjoying it….Good. Next comes is the multi-tier architecture where we consolidate different applications as per requirement like in a finance team they would need Tally and database records both. Moving further ahead, different systems like ERP, database, etc can be set up interlinked with one another to provide better facilities at remotest of the locations.

Jas: But what about the security aspects?cloud-gov

Me: That can be taken care by the firewalls, encryption techniques, etc.

Jas: Too good bro. Just one more question – what is this cloud thing which everyone is taking about these days?

Me: Cloud or cloud computing is where all the resources viz. data, applications, etc are accessible via a computer network like internet rather than from a local computer. Data is stored on Server Farms. It uses all of these systems architectures only which I have told you about.

Jas: It’s really nice to get to know all this. From now on, whenever you have a MIS lecture, after coming back, do let me know what all you studied.

Me: Sure bro, sure :)

*VGSOM (Vinod Gupta School of Management, IIT Kharagpur) is one of the leading B-Schools in India. For more information visit : http://www.som.iitkgp.ernet.in/
#MIS – Management Information Systems
P.S. – This blog entry has been done as an assignment for MIS course in 2011, autumn semester at VGSOM, IIT Kharagpur.
 
 

A line going for a walk!

23 Jul

You might be wondering what this post is all about. It’ll intrigue both drawers and budding artists.  Recently, when I was getting very bored on weekends, I started drawing. Then I suddenly recalled how I fancied making diagrams in project files for physics or chemistry. For the matter of fact, that was the only part I liked. After thinking and seeing lots of stuff about what to draw, I decided to make the popular cartoon characters Calvin and Hobbes.

100_0799

During that time, I was also reading the same; and could not resist drawing it. From then onwards I developed a lot of interest in drawing during my free times. There was this feeling of enjoyment in what I was doing. And this compelled me to draw even more and more. Designing enthralls me.

Yesterday, I was fishing the internet for learning to draw in 3D, and came across this wondrous engrossing site -http://www.mkisdraw3d.com/public/p_mksoi/In this regard, there is also a fascinating book that a friend of mine lent me: The Fundamentals of Drawing by Barrington Barber.

For those of you who seek designing as their career, must exercise some real 3d work. Do not let your talent go waste. Practice it and do it with style. Interest can become your career and just imagine doing what was once your hobby!

A line can do wonders when you give it a direction…

 

What do you love @Google

17 Jul

This google search portal was officially launched on 12th july. When you type a word and hit the “love” button, it’ll return results from all the major services from Google like Maps, Translate, SketchUp and around 20 more.

wdyl1

Technology used is called as “mash-up” . Technically, it’s single software or Web application that combines the features and information from multiple Web sites.  The challenging part is to fit the search the google products and anything the user types ; and Google has succeeded in same. There were many services that i didn’t know about until I tried this. On typing “love” in the search bar following are some amusing results I got-

wdyl2

1. Translate ‘love’ into 57 languages : Translate
2. Measure popularity of love on web : Trends
3. Find books on love : Books
4. Explore love in 3D: SketchUp
5. Watch videos of love: Youtube
6. See pictures of love: Image Search
7. Alert me about love: Alerts
8. Find love nearby: Maps
9. Find patents about love: Patent Search
10. Organize a debate about love: Moderator
11. Access love stuff on the web,faster : Chrome
12. Plan your love events: Calendar

There are few notable features about the search.  Everytime the engine is queried, search layout differs. There is also a handy scroll bar at left edge of the screen.
Some of these are google services that are not much known – services like SketchUp and Moderator. According to me wdyl will not be able to overpower google atleast for regular use. Wdyl is seen more as a way to educate people on the google’s various services.

Nevertheless, Google’s is going great.  :)

 
13 Comments

Posted in Tech