KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > auction > Main


1 //$Id: Main.java,v 1.6 2005/07/04 03:18:34 oneovthafew Exp $
2
package org.hibernate.auction;
3
4 import java.util.ArrayList JavaDoc;
5 import java.util.Date JavaDoc;
6 import java.util.HashSet JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9
10 import org.hibernate.FetchMode;
11 import org.hibernate.FlushMode;
12 import org.hibernate.LockMode;
13 import org.hibernate.Session;
14 import org.hibernate.SessionFactory;
15 import org.hibernate.Transaction;
16 import org.hibernate.cfg.Configuration;
17 import org.hibernate.cfg.Environment;
18 import org.hibernate.criterion.Example;
19 import org.hibernate.criterion.Expression;
20 import org.hibernate.criterion.MatchMode;
21
22
23 /**
24  * Demonstrate some useful features of Hibernate.
25  *
26  * @author Gavin King
27  */

28 public class Main {
29
30     private SessionFactory factory;
31
32     /**
33      * Demonstrates HQL projection/aggregation
34      */

35     public void viewAllAuctionsFast() throws Exception JavaDoc {
36         System.out.println("Viewing all auction item info");
37
38         Session s = factory.openSession();
39         Transaction tx=null;
40         try {
41             tx = s.beginTransaction();
42
43             List JavaDoc auctions = s.createQuery(
44                 "select new AuctionInfo( item.id, item.description, item.ends, max(bid.amount) ) "
45                 + "from AuctionItem item "
46                 + "left join item.bids bid "
47                 + "group by item.id, item.description, item.ends "
48                 + "order by item.ends desc"
49                 )
50                 .setMaxResults(100)
51                 .list();
52
53             Iterator JavaDoc iter = auctions.iterator();
54             while ( iter.hasNext() ) {
55                 AuctionInfo ai = (AuctionInfo) iter.next();
56                 System.out.println(
57                     "Auction: " + ai.getId() + " - " + ai.getDescription() +
58                     ", ends: " + ai.getEnds() +
59                     ", highest bid: " + ai.getMaxAmount()
60                 );
61             }
62             System.out.println();
63
64             tx.commit();
65         }
66         catch (Exception JavaDoc e) {
67             if (tx!=null) tx.rollback();
68             throw e;
69         }
70         finally {
71             s.close();
72         }
73     }
74
75     /**
76      * Demonstrates HQL with runtime fetch strategy
77      */

78     public void viewAllAuctionsSlow() throws Exception JavaDoc {
79         System.out.println("Viewing all auction item objects");
80
81         Session s = factory.openSession();
82         Transaction tx=null;
83         try {
84             s.setFlushMode(FlushMode.NEVER); //entirely optional!!
85
tx = s.beginTransaction();
86
87             List JavaDoc auctions = s.createQuery(
88                 "from AuctionItem item "
89                 + "left join fetch item.bids bid left join fetch bid.bidder "
90                 + "order by item.ends desc"
91                 )
92                 .setMaxResults(100)
93                 .list();
94
95             Iterator JavaDoc iter = new HashSet JavaDoc(auctions).iterator();
96             while ( iter.hasNext() ) {
97                 AuctionItem auction = (AuctionItem) iter.next();
98                 System.out.println(
99                     "Auction: " + auction.getId() + " - " + auction.getDescription() +
100                     ", ends: " + auction.getEnds() +
101                     ", bids: " + auction.getBids()
102                 );
103             }
104             System.out.println();
105
106             tx.commit();
107         }
108         catch (Exception JavaDoc e) {
109             if (tx!=null) tx.rollback();
110             throw e;
111         }
112         finally {
113             s.close();
114         }
115     }
116
117     /**
118      * Demonstrates transitive persistence with detached object support
119      */

120     public void bidOnAuction(User bidder, AuctionItem item, float amount) throws Exception JavaDoc {
121         System.out.println("Creating a new bid for auction item: " + item.getId() + " by user: " + bidder.getId() );
122
123         Session s = factory.openSession();
124         Transaction tx=null;
125         try {
126             tx = s.beginTransaction();
127
128             s.lock(item, LockMode.NONE);
129             s.lock(bidder, LockMode.NONE);
130
131             Bid bid = new Bid();
132             bid.setBidder(bidder);
133             bid.setDatetime( new Date JavaDoc() );
134             bid.setAmount(amount);
135             bid.setItem(item);
136             bidder.getBids().add(bid);
137             item.getBids().add(bid);
138
139             tx.commit();
140         }
141         catch (Exception JavaDoc e) {
142             if (tx!=null) tx.rollback();
143             throw e;
144         }
145         finally {
146             s.close();
147         }
148     }
149
150     /**
151      * Demonstrates detached object support
152      */

153     public void changeUserDetails(User user) throws Exception JavaDoc {
154         System.out.println("Changing user details for: " + user.getId() );
155
156         Session s = factory.openSession();
157         Transaction tx=null;
158         try {
159             tx = s.beginTransaction();
160
161             s.merge(user);
162
163             tx.commit();
164         }
165         catch (Exception JavaDoc e) {
166             if (tx!=null) tx.rollback();
167             throw e;
168         }
169         finally {
170             s.close();
171         }
172     }
173
174     /**
175      * Demonstrates automatic dirty checking
176      */

177     public void changeItemDescription(Long JavaDoc itemId, String JavaDoc description) throws Exception JavaDoc {
178         System.out.println("Changing auction item description for: " + itemId );
179
180         Session s = factory.openSession();
181         Transaction tx=null;
182         try {
183             tx = s.beginTransaction();
184
185             AuctionItem item = (AuctionItem) s.get(AuctionItem.class, itemId);
186             if (item==null) throw new IllegalArgumentException JavaDoc("No item for the given id: " + itemId);
187             item.setDescription(description);
188
189             tx.commit();
190         }
191         catch (Exception JavaDoc e) {
192             if (tx!=null) tx.rollback();
193             throw e;
194         }
195         finally {
196             s.close();
197         }
198     }
199
200     /**
201      * Demonstrates query by criteria with runtime fetch strategy
202      */

203     public void viewUserAuctions(Long JavaDoc sellerId) throws Exception JavaDoc {
204         System.out.println("Viewing user and auctions: " + sellerId);
205
206         Session s = factory.openSession();
207         Transaction tx=null;
208         try {
209             tx = s.beginTransaction();
210
211             List JavaDoc list = s.createCriteria(User.class)
212                 .add( Expression.eq("id", sellerId) )
213                 .setFetchMode("auctions", FetchMode.JOIN)
214                 .list();
215
216             if (list.size()==0) throw new IllegalArgumentException JavaDoc("No user for the given id: " + sellerId);
217             User user = (User) list.get(0);
218             System.out.println(
219                 "User: " + user.getId() + " - " + user.getName() +
220                 ", email: " + user.getEmail() +
221                 ", auctions: " + user.getAuctions()
222             );
223
224             tx.commit();
225         }
226         catch (Exception JavaDoc e) {
227             if (tx!=null) tx.rollback();
228             throw e;
229         }
230         finally {
231             s.close();
232         }
233     }
234
235     /**
236      * Demonstrates query by example
237      */

238     public void viewAuctionsByDescription(String JavaDoc description, int condition) throws Exception JavaDoc {
239         String JavaDoc msg = "Viewing auctions containing: " + description;
240         if (condition>0) msg += " with condition: " + condition + "/10";
241
242         AuctionItem item = new AuctionItem();
243         item.setDescription(description);
244         item.setCondition(condition);
245
246         Session s = factory.openSession();
247         Transaction tx=null;
248         try {
249             tx = s.beginTransaction();
250
251             Iterator JavaDoc iter = s.createCriteria(AuctionItem.class)
252                 .add( Example.create(item)
253                     .enableLike(MatchMode.ANYWHERE)
254                     .ignoreCase()
255                     .excludeZeroes()
256                 )
257                 .list()
258                 .iterator();
259
260             System.out.println(msg);
261             while ( iter.hasNext() ) {
262                 item = (AuctionItem) iter.next();
263                 System.out.println("Item: " + item.getId() + " - " + item.getDescription() );
264             }
265             System.out.println();
266
267             tx.commit();
268         }
269         catch (Exception JavaDoc e) {
270             if (tx!=null) tx.rollback();
271             throw e;
272         }
273         finally {
274             s.close();
275         }
276     }
277
278     /**
279      * Demonstrates transitive persistence
280      */

281     public void createTestAuctions() throws Exception JavaDoc {
282         System.out.println("Setting up some test data");
283
284         Session s = factory.openSession();
285         Transaction tx = s.beginTransaction();
286
287         User seller = new User();
288         seller.setUserName("xam");
289         seller.setName( new Name("Max", new Character JavaDoc('R'), "Andersen") );
290         seller.setEmail("max@hibernate.org");
291         seller.setPassword("******");
292         seller.setAuctions( new ArrayList JavaDoc() );
293         s.save(seller);
294         User bidder1 = new User();
295         bidder1.setUserName("1E1");
296         bidder1.setName( new Name( "Gavin", new Character JavaDoc('A'), "King") );
297         bidder1.setEmail("gavin@hibernate.org");
298         bidder1.setPassword("******");
299         bidder1.setBids( new ArrayList JavaDoc() );
300         s.save(bidder1);
301         User bidder2 = new User();
302         bidder2.setUserName("steve");
303         bidder2.setName( new Name("Steve", null, "Ebersole") );
304         bidder2.setEmail("steve@hibernate.org");
305         bidder2.setPassword("******");
306         bidder2.setBids( new ArrayList JavaDoc() );
307         s.save(bidder2);
308
309         for ( int i=0; i<3; i++ ) {
310             AuctionItem item = new AuctionItem();
311             item.setShortDescription("Auction " + i);
312             item.setDescription("the auction item number " + i);
313             item.setEnds( new Date JavaDoc() );
314             item.setBids( new ArrayList JavaDoc() );
315             item.setSeller(seller);
316             item.setCondition(i*3 + 2);
317             for ( int j=0; j<i; j++ ) {
318
319                 Bid bid = new Bid();
320                 bid.setBidder(bidder1);
321                 bid.setAmount(j);
322                 bid.setDatetime( new Date JavaDoc() );
323                 bid.setItem(item);
324                 item.getBids().add(bid);
325                 bidder1.getBids().add(bid);
326
327                 Bid bid2 = new Bid();
328                 bid2.setBidder(bidder2);
329                 bid2.setAmount( j + 0.5f);
330                 bid2.setDatetime( new Date JavaDoc() );
331                 bid2.setItem(item);
332                 item.getBids().add(bid2);
333                 bidder2.getBids().add(bid2);
334             }
335             seller.getAuctions().add(item);
336             mainItem = item;
337         }
338         mainBidder = bidder2;
339         mainSeller = seller;
340
341         BuyNow buyNow = new BuyNow();
342         buyNow.setAmount(1.2f);
343         buyNow.setDatetime( new Date JavaDoc() );
344         buyNow.setBidder(mainBidder);
345         buyNow.setItem(mainItem);
346         mainBidder.getBids().add(buyNow);
347         mainItem.getBids().add(buyNow);
348
349         tx.commit();
350         s.close();
351     }
352
353     static AuctionItem mainItem;
354     static User mainBidder;
355     static User mainSeller;
356
357     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
358
359         final Main test = new Main();
360
361         Configuration cfg = new Configuration()
362             .addClass(AuctionItem.class)
363             .addClass(Bid.class)
364             .addClass(User.class)
365             .setProperty(Environment.HBM2DDL_AUTO, "create");
366         //cfg.setProperty("hibernate.show_sql", "true");
367

368         test.factory = cfg.buildSessionFactory();
369
370         test.createTestAuctions();
371         test.viewAllAuctionsSlow();
372
373         test.viewAllAuctionsFast();
374         test.bidOnAuction(mainBidder, mainItem, 5.5f);
375         test.viewAllAuctionsFast();
376
377         test.viewUserAuctions( mainSeller.getId() );
378         mainSeller.setEmail("max@jboss.org");
379         test.changeUserDetails(mainSeller);
380         test.changeItemDescription(mainItem.getId(), "new description");
381         test.viewUserAuctions( mainSeller.getId() );
382
383         test.viewAuctionsByDescription("It", 0);
384         test.viewAuctionsByDescription("DESC", 3);
385         test.viewAuctionsByDescription("DESC", 8);
386
387         test.factory.close();
388
389     }
390 }
391
Popular Tags