Discussions

News: Book Excerpt: Java Persistence with Hibernate

  1. Book Excerpt: Java Persistence with Hibernate (60 messages)

    Java Persistence with Hibernate, by Christian Bauer and Gavin King and published by Manning Press, explores Hibernate by developing an application that ties together hundreds of examples, digging into Hibernate 3.2's rich implementation of the Java Persistence API. This excerpt from the book covers legacy databases and custom SQL - how you can override Hibernate's natural mappings to conform to a pre-existing database, and how to interact with an "existing legacy database or a wierd or broken schema."
    Two types of problems are considered: problems that relate to the changing business requirements (which generally can't be solved without schema changes) and problems that relate only to how you wish to represent the same business problem in your new application (these can usually, but not always, be solved without database schema changes).

    Threaded Messages (60)

  2. They did it again![ Go to top ]

    I'm a experienced hibernate user, I read HiA two years ago however I found the new book very interesting. Specially the examples with Jboss Embedded and the Seam chapter.
  3. Re: They did it again![ Go to top ]

    December 2007 !!?? wouah !!
  4. Did authors cover the ObjectNotUniqueException problem in this book (in the previous the didn't)? The only working solution for "composite relations" and ObjectNotUniqueException I found on hibernate forum was the following (and it starts with AVOID)... I can suggest try to AVOID Non composite relations via collections i.e. if you have Container and Item classes and Item can exist without Container or can present in more than ONE container. DO NOT make collection of items in Container and DO NOT make collection of containers in Item class. Instead you'll have to create third class and hold relation information in it. Relations via collections work well only if you have composite relation between classes. i.e. Class Container contains collection of Item and item can be accesses only my via containers methods and can't exists without Container. the full discussion is here http://forum.hibernate.org/viewtopic.php?t=951517&highlight=nonuniqueobjectexception --Mark
  5. This time they mention(once) that the most popular Hibernate Exception exist but didn't show how to fix the problem with non composite relations. IMHO The situation with NonUniqueObjectException remains. All I can suggest is "Try to AVOID Non composite relations via collections". I hope hibernate guys will suggest the other solution. Regards, Vitaliy S
  6. I have a difficult time even understanding what the problem is you want a solution for. The right place to get help on this is probably http://forum.hibernate.org
  7. I have a difficult time even understanding what the problem is you want a solution for. The right place to get help on this is probably http://forum.hibernate.org
    If you read the link to post(http://forum.hibernate.org/viewtopic.php?t=951517&highlight=nonuniqueobjectexception) carefully you'll understand that Hibernate Team ignored that question(as well as several questions on same theme) on the forum.
  8. Uhm, you realize that the questions on this forum thread are just repeated over and over (this is not uncommon...) and that the answer is already there? Anyway, can you please move this to the Hibernate forum and open a _new_ thread there? I'm sure someone will help you if you post your code, mapping etc. From your vague descriptions you probably have to read up on object states, reattachment, merging, and cascading.
  9. Uhm, you realize that the questions on this forum thread are just repeated over and over (this is not uncommon...) and that the answer is already there?
    If you check the forum you'll probably realize that this question was ignored (more that once). Why should I post this question again? I found the solution and posted it to hibernate forum. It seems Guys like Mark want another solution and they didn't find it in the book. If you want to provide solution, go ahead, I think guys like Mark and me will thank you for that.
    From your vague descriptions you probably have to read up on object states, reattachment, merging, and cascading.
    From you vague descriptions I see you try to promote your book ;-)
  10. I don't even understand the problem. You need to go to the Hibernate forum and post CODE and MAPPINGS and so on. My magic crystal doesn't work because of the sun flares last week and I've never been really good at mind reading. So please, take whatever Hibernate questions you have to the right place and provide the necessary information. This thread is about a book and I'd love to get more feedback on that.
  11. I don't even understand the problem. You need to go to the Hibernate forum and post CODE and MAPPINGS and so on. My magic crystal doesn't work because of the sun flares last week and I've never been really good at mind reading. So please, take whatever Hibernate questions you have to the right place and provide the necessary information.

    This thread is about a book and I'd love to get more feedback on that.
    Christian. Mark asked the question about _your_ book. I gave the answer to him - The book doesn't provide enough information on problem we discussed on hibernate forum. Next you appear with your lost magic crystal problem. I'm not Google, I can't help you with the search of your crystal, sorry.
  12. I gave the answer to him - The book doesn't provide enough information on problem we discussed on hibernate forum.
    The book covers object states, merging, and reattachment in so much detail that my editor even asked if this wouldn't be too much. It certainly provides enough information to answer whatever questions a developer might have about this particular subject. I can't comment if a particular problem is explicitly covered, because I don't understand what the problem in question is. The one year old forum thread that is being quoted over and over here does not include any mappings or code that would help me see the issue. It's also about Hibernate 2. If you understand what the forum thread is about, and you also think the book doesn't help... nothing much I can do I guess except hope that someone explains it to me.
  13. Nothing much I can do I guess except hope that someone explains it to me
    Ok, I'll try to explain. Consider a situation where you have two persistent classes with bidirectional association: container and component containers Con1 and Con2 both contain component Com1. If you try to load Con1 and Con2 you'll receive exception. To AVOID this situation I suggested to AVOID using non composite associations. To make given example work without problems we must create third class that stores the information about component/container relations.
    The one year old forum thread that is being quoted over and over here does not include any mappings or code that would help me see the issue. It's also about Hibernate 2.
    I wounder does any body beside Christian think that this sample needs mappings or code? The situation remains in Hibernate 3 (as was written in same thread).
  14. I actually have some experience answering questions about Hibernate and I still don't get it. Please post mappings and code etc. to the Hibernate forum.
  15. And they did! public void method(MyObject obj) { MyObject persistentCopy = session.merge(obj); // working with persistentCopy // no need obj anymore } Really this IS an example of "transparent persistance", no transparency at all! Really guys, it's kinda stupid to worry about "is my precious object in persistance context?". All I want is to attach it to session and continue work with IT, not its copy (if I want a copy I'll use clone()).
  16. It's not a copy you get back from merge(). It's a reference to an instance that is now the current state of your system, after merging. You merged the state of two objects. You get a handle on the result of that operation. If you don't want merging, use reattachment. Of course, Hibernate will then complain with a NonUniqueObjectException if you put, through loading, reattachment, cascading, whatever, two colliding instances (objects that represent the same database row) in the same persistence context. What other options do you need?
  17. Sure it's a copy - a persistent one. I need the only option(and think most people want the same) - non-complaining reattachement. I say session - reattach and it's the session's rensponsibility to handle attached/non-attached object issues, not mine.
  18. And how is that supposed to work? What is Hibernate supposed to do if the Session already contains the same thing? Not throw an exception and just ignore the reattachment? Merge stuff automatically and not return you a handle to the current state? At some point you will have to make a decision that no tool can make for you.
  19. By the way, this thread shows why we recommend to implement conversations with an extended persistence context and not with detached objects: - you need to understand detached object state - difficult to understand reattachment, more so with cascading state - difficult to understand merging, more so with cascading state - you need to implement equals()/hashCode() correctly So if you find all of this too much, simply don't do it and use the alternative strategy.
  20. And how this exeption should be handled? Both books have notes over and over "Dont work with sesssion after Hibernate exceeption was throwed". And what i suppose to do? Rollback everything, close everything, report to everyone "hibernate guys think you should not work with this object"? In this case automatic merging (with versioning) is the lesser evil.
  21. PDf ebook version is very handy[ Go to top ]

    I love the PDF ebook version. It's much easier to search the ebook than the paper version and you don't have to carry the bulky book around with you. If you buy the book off of Manning's site you can buy the PDF ebook or the printed version with the ebook. Amazon doesn't mention the ebook, however.
  22. How thick is it ?[ Go to top ]

    How thick is this book ? Because the price is quite high (59.99 $). Amazon doesn't sell the PDF, but the price is better (39.59 $). Manning should make a special price on the PDF for the owners of "Hibernate In Action" (and a special subscription price for the fans of the "In Action" serie ;-)). Me too, I like the PDF for browsing and searching, but I prefer the printed edition for reading. Therefore, I'm glad the dollar is not very high compared to the euro at the moment.
  23. Re: How thick is it ?[ Go to top ]

    Thickest hibernate book available?! http://blog.hibernate.org/cgi-bin/blosxom.cgi/Christian%20Bauer/general/hibernatebooks.html
  24. Re: How thick is it ?[ Go to top ]

    Woaw ! It's three times the size of the previous one ! Even if it's half as valuable (and I expect this is not the case), you don't loose your money. I thought it was just a rework of the previous edition using JPA, but it seems there is much more inside. Of course, I'll buy it then. Thank you all for having helped me make a decision.
  25. Re: How thick is it ?[ Go to top ]

    How thick is this book ? Because the price is quite high (59.99 $). Amazon doesn't sell the PDF, but the price is better (39.59 $). Manning should make a special price on the PDF for the owners of "Hibernate In Action" (and a special subscription price for the fans of the "In Action" serie ;-)).
    Me too, I like the PDF for browsing and searching, but I prefer the printed edition for reading. Therefore, I'm glad the dollar is not very high compared to the euro at the moment.
    If Hibernate is key to your project, you must buy this book. More importantly you must read it! In fact if I was leading a team, and they picked Hibernate as the ORM, I would insist that they take a day or two and read this book before getting started. Just think of the money that could be saved by using Hibernate correctly. Seriously, $60.00 is a bargain, compared to reworking a broken persistence layer. There are some caveats in using Hibernate. (Avoiding N+1, Avoiding cartesian product queries, Avoiding LazyInitialization errors, Tunning, Debugging, Understanding the architecture well enough to debug effectively, etc.)
  26. Re: How thick is it ?[ Go to top ]

    I would insist that they take a day or two and read this book before getting started.
    Speed Reading contest?
  27. Re: How thick is it ?[ Go to top ]

    30 pages per hour * 10 hours is 300 pages a day.... 8 hours at work. 1 hour on the train to work. 1 hour on the train from work. That is 600 pages in two days... It may not be the whole book, but it is a good start. Then they can read the rest on the train ride in.... :o)
  28. Re: How thick is it ?[ Go to top ]

    30 pages per hour * 10 hours is 300 pages a day....

    8 hours at work. 1 hour on the train to work. 1 hour on the train from work.

    That is 600 pages in two days...

    It may not be the whole book, but it is a good start.

    Then they can read the rest on the train ride in....

    :o)
    30 pages per hour is considering you don't get distracted and are also reading some novel:-) Does this book read like a novel? :-) Ilya
  29. Re: How thick is it ?[ Go to top ]

    I would insist that they take a day or two and read this book before getting started.


    Speed Reading contest?
    Okay... maybe a day or two to get started and then come back to it for a few hours each morning until you get it read.....
  30. Can you please email me the .pdf version of the book if u have. can you mail me at chhabradeepti at hotmail dot com Thanks in advance Deepti
  31. Many thanks to Gavin and Christian for a great job they're doing.
  32. about the source code[ Go to top ]

    I am reading the book, The source code should be downloaded on http://www.manning.com/bauer2 But, I can't visit it. Now, I am in China. Who can help me download it? and send it to my mailbox. My mail is: qixiangnj at gmail dot com Thanks! Best Regards, Thomas Che
  33. Great technical resource[ Go to top ]

    I downloaded the PDF a month or two ago (maybe longer). I spent $70.00 getting it printed and bound. I then read pretty much the whole thing cover to cover. It was the unedited version of the book. Later I used it to figure out how to call Oracle Stored Procedures. Later still I used it to figure out how to change the SQL to load an object. This book is a great technical resource. I highly recommend it. I can't imagine doing Hibernate development without it. It is quite a bit larger than the original (Hibernate in Action), then again Hibernate has grown as well. BTW When I ordered the book, I ordered the printed book/PDF bundle. This way when the final version came out, I would get it and not have to reprint the PDF. I was told that when the printed book became available it would be sent. I heard that the books are already at the book stores. Thus, even though I pre-ordered the book in good faith. The bookstores received the hard copies before I did. This of course is a Manning publishing issue not a Gavin/Christian issue.
  34. Re: Great technical resource[ Go to top ]

    Rick, You should probably check with Manning. I got my printed copy over a week ago (through the early access program).
  35. Re: Great technical resource[ Go to top ]

    I downloaded the PDF a month or two ago (maybe longer). I spent $70.00 getting it printed and bound. I then read pretty much the whole thing cover to cover. It was the unedited version of the book.

    Later I used it to figure out how to call Oracle Stored Procedures. Later still I used it to figure out how to change the SQL to load an object.

    This book is a great technical resource. I highly recommend it. I can't imagine doing Hibernate development without it.

    It is quite a bit larger than the original (Hibernate in Action), then again Hibernate has grown as well.

    BTW When I ordered the book, I ordered the printed book/PDF bundle. This way when the final version came out, I would get it and not have to reprint the PDF. I was told that when the printed book became available it would be sent. I heard that the books are already at the book stores. Thus, even though I pre-ordered the book in good faith. The bookstores received the hard copies before I did. This of course is a Manning publishing issue not a Gavin/Christian issue.
    Same experience here - actually, the only other time I ordered something through their MEAP, I didn't get the book in a reasonable amount of time either. Kinda sucks to pay extra and early for the book, only to get it months after it has come out. Manning's logistical problems aside, the eBook hasn't disappointed - in terms of valuable information, it is one of the better books I've read in the past few years. Christian and Gavin did an excellent job, and I highly recommend the book.
  36. I also don't understand the question that is being asked here, and have to agree with Christian's comment about crystal balls. Certainly I don't know what a "composite relation" is, or why anyone things it relates to NonUniqueObjectExceptions. However, to put all this in context: The ONLY reason why anyone ever gets NonUniqueObjectExceptions, or LazyInitializationExceptions is because they are using a stateless architecture. If you use an extended persistence context with Hibernate, you will simply never meet these beasties. That is why we created Seam. I am utterly sick out of my brain of Hibernate getting the blame for NUOE and LIE when it is *not Hibernate's fault*. Hibernate has extended persistence contexts. It is the fault of *your stateless architecture* for not letting you use them. So go and check out Seam and read up on conversations and conversation-scoped persistence contexts, and you will discover how much easier Hibernate can be!
  37. I also don't understand the question that is being asked here, and have to agree with Christian's comment about crystal balls. Certainly I don't know what a "composite relation" is, or why anyone things it relates to NonUniqueObjectExceptions.
    Composition is a form of aggregation with strong ownership and coincident lifetime of part with the whole. If you'll try to implement the example I've described above you'll understand what I mean. E.g. you've got Groups and Users with not composite bidirectional association group1 contains user1 group2 contains user1 too if you have a query that returns all groups you'll get NonUniqueObjectException The way to avoid this problem is to create GroupUserRelation class that stores User/Group relations.
    I am utterly sick out of my brain of Hibernate getting the blame for NUOE and LIE when it is *not Hibernate's fault*
    I understand the nature of problem and I never said that it is hibernate fault. I just try to point that problem exist and it would be nice if we have more comments, best practices etc. I was surprise the book doesn't cover it well enough. IMHO The FAQ on hibernate site doesn't cover it well enough too. You experience tells the same. Yes, there are a lot of people that don't understand well why this problem appears.
  38. This description still doesn't make sense. Code and mappings, on the Hibernate forum please.
  39. Well, he's talking about the classic situation where you have two disparate object graphs from two sources that need to be worked with in the same session. Somewhere in those two graphs, you will end up having the same object referenced by two different objects. Hibernate doesn't handle that well (and can't really, I have to agree with Christian & Gavin on that). Merge is probably the closest thing, but if one of the objects is modified & the other isn't, that will error out -- so it isn't a reliable solution. Hibernate could probably help out a bit more here if it compared merged objects to the DB (essentially ignore the merge of the unchanged object in favor of the changed object in cases where you merge two objects that represent the same row). But there are performance implications there that not everyone would want to accept. Could also create hard to find bugs in cases where an object is changed in one spot and then changed back elsewhere. Not something hibernate can realistically control. I am using hibernate in a fairly heavily threaded swing application, so I have had to wrestle with this particular problem a bunch. I think the best solution where you need to use hibernate in this manner is 1. do not use cascading (you might get away with it in special parent/child situations, otherwise, don't) and 2. avoid using detached objects. 1. Means you need to write a bit more code to explicitly tell hibernate what you want to save. 2. means that instead of assigning an object to a session, you might use the get method on the session to get a nice, clean, object graph. Basically you are relying on the hibernate cache instead of detached objects you pass around. Of course 2 doesn't work in cases where you have changed the object -- there you need to make sure you assign them to the session right after it is opened (turning off cascading makes this a *LOT* more predictable). That has worked for quite some time for me anyway. Just trade off a little ease of use for a bit more control. Also, Gavin Seam is a neat framework, but there are cases (like certain kinds of web services, swing apps, and so on) where hibernate can't be used in a nice workflow-type, single-threaded, fashion. Sometimes developers are going to want to pass an object from one user session to another (crossing that persistent context boundary). Or they are going to need to thread some operation and pass the results back to be saved, whatever. We all have tough requirements to meet sometimes. That's where this type of stuff comes up, and where a persistent context fails to help one bit. It is also a major weak point in the documentation, and best practice talks. I see a lot of people trying to pass a possibly changed object to a session they know basically nothing about (a consequence of highly generalized systems). You can't do that in Hibernate (reliably, 100% of the time, with no exceptions) without saving to the db in another session and reloading in the "unknown state" session (and possibly loosing an update there). Docs should mention gotcha's like that (which are not going to be obvious to first-time users) -- they don't last time I checked, which I admit has been a little while.
  40. Somewhere in those two graphs, you will end up having the same object referenced by two different objects. Hibernate doesn't handle that well...
    dang lack of an edit button! having the same row referenced by two different objects
  41. Sometimes developers are going to want to pass an object from one user session to another (crossing that persistent context boundary). Or they are going to need to thread some operation and pass the results back to be saved, whatever.
    I'm pretty much a total neophyte when it comes to desktop apps, but I'm inclined to try and think about the problem in the same way I'm modelling Ajax. ie. conversation == toplevel window or tab == persistence context So there is a single conversation (hence a single peristence context) per "window". I'm speaking approximately, of course - little popups would share the conversation of the parent, larger child windows might be a nested conversation, etc. Concurrency within a single conversation would be handled by serializing event processing before it reaches the business layer - ie. you can do some simple UI processing without and synchronization, but before you go off and start hitting the PC, you need to serialize the events. Events in different conversations do not need to be serialized. But access to shared "global" state needs explicit synchronization (never, ever use "synchronized" for this, it has no deadlock detection - see Seam's @Synchronized annotation for the Right Way to do it). So, given that model, let's see where it breaks: (0) It breaks if I try to modify global state in the conversation: you should never, ever try to associate any globally visible object with a conversation-scope persistence context! If you have to change a global object, modify a copy, and replace the globally-visible object after the update was successful. (1) It breaks if I need to pass an object between two different conversations (or even user sessions). IMO, as long as you get your conversation model correct, and you follow (0), this should be very, very rare to need to do this. Like, super-rare. If you absolutely *have* to do it, then merge() is really quite a reasonable solution and is not vulnerable to NUOE. (2) It breaks if I have some extremely long-running work to do in an event handler, that would block other threads. I would expect this to be rare in most desktop applications, but in general it is a case that you have got to be able to handle. Long running processing needs to be done asynchronously, in another thread, and its own conversation. (A Seam @Asynchronous method is an easy way.) Then you are left with the problem of getting the changes from the asynchronous thread back into the first conversation that we can from. There are two cases: (a) the async thread was able to make the changes persistent - then one approach is to just refresh the right objects in the original conversation (b) the async thread is not allowed to make the changes persistent - well, then you have to use merge() Either case could be messy if you've let the user change the same objects that were changed by the async thread. But I'm going to call that a bug in your application :-) (3) It breaks if you have some kind of crazy stuff where a nested conversation (child window of some kind) is supposed to work by snapshotting the objects from the outer conversation and letting the user freely edit them without the changes being visible in the outer conversation until the user explicitly says so. This example calls for copying the whole persistence context, and then later merging all its objects back into the original persistence context. (Currently neither Hibernate nor Seam have any kind of special support for this, but I can see it being something worth supporting in future.) It turns out that this case is exactly equivalent to (2) (b). I can't really think of any other usecases that would break the model...? So you're right, conversation-scoped persistence contexts don't completely solve *every* problem - there are still some scenarios for the use of merge(). But to me it looks like these cases are sufficiently rare that its not unreasonable to think that merge() is "good enough".
  42. Merging scared the bejesus out of me. We've been able to avoid the situation altogether for 3 years with our couple of (extensively used) Hibernate apps. Seam would probably make our lives easier, but going back now wouldn't be cheap...
  43. I'm pretty much a total neophyte when it comes to desktop apps
    Well, that scared me as I try to "desktop" applications as much as possible and only do a "webapp" where there is no other choice. Anyway, because I was a little lost, I'm not sure this covers "desktop" apps where the code is split between the client and the server. In that instance POJOs are modified on the client and persisted on the server. That being said, I've not had problems with using detached objects. Hopefully the new book spends time on Conversations, because I have not touched those at all.
  44. Anyway, because I was a little lost, I'm not sure this covers "desktop" apps where the code is split between the client and the server. In that instance POJOs are modified on the client and persisted on the server.
    Yeah, currently there is no good implementation of conversations/extended-persistence-context-management for such an architecture. It's something we've often talked about working on, though. Its definitely not an impossible problem.
  45. Hopefully the new book spends time on Conversations, because I have not touched those at all.
    Well, there is actually a whole part (several chapters, one exclusively) about "conversational object processing". :)
  46. I agree with just about everything you stated in your post Gavin. But to throw a couple things out there:
    (a) the async thread was able to make the changes persistent - then one approach is to just refresh the right objects in the original conversation

    (b) the async thread is not allowed to make the changes persistent - well, then you have to use merge().
    A is the better choice. That is more or less the approach I use. B is fine so long as you are not cascading -- the risk of lost updates is too great. For example, two concurrent threads are doing some processing. One modifies a row, the other merely loads it for some reason (perhaps on the way to some other object, or as part of a list that is intialized in full). If you don't merge in the right order, update is gone. Still possible even without cascading, but there you have a bunch more control and the bug will be more obvious if it ever crops up. Cascading is a tad evil if you aren't in a straightforward conversation-scoped context.
    But to me it looks like these cases are sufficiently rare that its not unreasonable to think that merge() is "good enough".
    Yep. Hibernate 3 fixed a lot of problems in these enviroments with its various tweaks & new functionality. Doco is part that could use a bit more warning, tips, and info (which is what I thought I said in the last post :)
  47. Somewhere in those two graphs, you will end up having the same object referenced by two different objects. Hibernate doesn't handle that well (and can't really, I have to agree with Christian & Gavin on that)
    Considering the given example: Container1 contains Component1 and Container2 contains same Component1. Why during processing the query hibernate can not create one object Component1 and put it in both Containers?
  48. What does "container", "component", and "contains" mean? Code? Hibernate Forum?
  49. What does "container", "component", and "contains" mean? Code? Hibernate Forum?
    Very sad to see how book authors pretend not knowing what are container, component and composite/non-composite associations. If to avoid the problem with non-composite associations we should use JPA/EJB3 why to buy this book instead of EJB3 book?
  50. What does "container", "component", and "contains" mean? Code? Hibernate Forum?

    Very sad to see how book authors pretend not knowing what are container, component and composite/non-composite associations.

    If to avoid the problem with non-composite associations we should use JPA/EJB3 why to buy this book instead of EJB3 book?
    That's a really non-constructive way to ask a question. Loose the flames, it is to everyone's benefit.
  51. Somewhere in those two graphs, you will end up having the same object referenced by two different objects. Hibernate doesn't handle that well (and can't really, I have to agree with Christian & Gavin on that)


    Considering the given example:
    Container1 contains Component1 and Container2 contains same Component1.

    Why during processing the query hibernate can not create one object Component1 and put it in both Containers?
    Containter1 is an object that references another object, Component1. Component2 is an object (presumably of the same class) that also references Component2. It isn't as concrete as code, but it seems straightforward to me. Anyway, Hibernate cannot do that because the two sessions that performed the queries for Container1 and Container2 could be (and probably are if this isn't a command-line application) in different threads. Returning the same object, which could then conceivably be modified in two different threads, is a big no-no. For one, hibernate-managed objects are not usually (I'd bet 99%) threadsafe. Even if they are, you would have to *also* write the code that modifies them in threadsafe manner otherwise your application could save or make decisions on invalid data (just because two threads can't update the same object at the same time doesn't make the entire operation is threadsafe). If hibernate placed those types of requirements on programmers, it would never have gotten off the ground.
  52. Somewhere in those two graphs, you will end up having the same object referenced by two different objects. Hibernate doesn't handle that well (and can't really, I have to agree with Christian & Gavin on that)


    Considering the given example:
    Container1 contains Component1 and Container2 contains same Component1.

    Why during processing the query hibernate can not create one object Component1 and put it in both Containers?


    Containter1 is an object that references another object, Component1. Component2 is an object (presumably of the same class) that also references Component2.

    It isn't as concrete as code, but it seems straightforward to me.

    Anyway, Hibernate cannot do that because the two sessions that performed the queries for Container1 and Container2 could be (and probably are if this isn't a command-line application) in different threads. Returning the same object, which could then conceivably be modified in two different threads, is a big no-no.
    It seems to me Nat was talking about single query. But even in case of several queries why not to throw Exception only in case it retrieves object that was already retrieved and _modified_? PS If Gavin was so tied of people blaming Hibernate for NonUniqueObjectException why he wrote almost nothing about it in the new book? I think good book should tell us about pitfalls as well.
  53. It seems to me Nat was talking about single query.
    Well, in a single query, it *would* return the same object, Component1, attached to both Container1 and Container2. That is also true for multiple queries inside the same session. Or multiple queries across sessions if you associated Component1 with the session before the second query. So I don't think he was talking about one query, or multiple queries across the same session. The question only makes sense if you are talking about two completely separate sessions.
    But even in case of several queries why not to throw Exception only in case it retrieves object that was already retrieved and _modified_?
    That is what merge is for (actually it will overwrite regardless, even if you merge an unmodified object over a modified one, which is why merge+cascade is dangerous). The reason you can't do that on Save/Update/SaveOrUpdate is similar to a cache coherency problem. If you allowed that, then what do you do with the unmodified object? Copy the state of the modified object over it? How do you keep the two objects in sync? Do you replace any references to the unmodified object in favor of the modified one? What if the unmodified object is referenced somewhere hibernate doesn't know about? That's why merge copies the state & returns a persistent object. Making it the framework user's responsibility to handle all that (where it should be).
  54. That is what merge is for (actually it will overwrite regardless, even if you merge an unmodified object over a modified one, which is why merge+cascade is dangerous).
    No, it won't. You will get a StaleObjectStateException if you try to merge onto a modified instance, because Hibernate can't know what state you want to keep and which to overwrite.
  55. That is what merge is for (actually it will overwrite regardless, even if you merge an unmodified object over a modified one, which is why merge+cascade is dangerous).


    No, it won't. You will get a StaleObjectStateException if you try to merge onto a modified instance, because Hibernate can't know what state you want to keep and which to overwrite.
    Oops, yep, found a small bug in a test case I wrote to remind myself. Funnily enough, it doesn't really change the meaning. A potentially random-looking exception (random in that it would happen on certain rows and not others) is almost as bad as lost updates. Still, not something hibernate can control, just not a good idea to use merge with cascades in certain use cases.
  56. I absolutely have no idea what you guys are talking about. :) Containers, components, queries, objects, etc... and now threads? Can't you just write five lines of code to show what you mean without any ambiguity and riddles?
    PS If Gavin was so tied of people blaming Hibernate for NonUniqueObjectException why he wrote almost nothing about it in the new book? I think good book should tell us about pitfalls as well.
    ?!? Have you read the book?
  57. Hello, last week I was meeting an interesting problem of our customer. He wants to use custom sql queries in conjunction with annotations - so no hibernate mapping file but annotations only. In the excerpt chapter which covers custom sql, I could not find mentioning of the syntax to be used for annotation based custom sql queries. Is this not covered by the book because it's already part of the hibernate reference (http://www.hibernate.org/hib_docs/annotations/reference/en/pdf/hibernate_annotations.pdf)? Or is it just covered in a different chapter? Maybe I could recommend this book to our customer but I want to know whether this particular topic is covered, because it's really on of the requirements to use those (very complex) custom sql queries. Thanks for your advice! Cheers, René
  58. The custom SQL support for annotations was just added a few weeks ago to Hibernate Annotations. At the time of writing it just wasn't there. But the new annotations work really the same way as the XML and I think that the value is in knowing _when_ and _how_ to replace the automatically generated SQL. It's easy to decide where you put your custom SQL strings and there is really not much difference between annotations and XML.
  59. I think TSS should really provide much better search capability (especially for news) to its readers. e.g. I have to make a post here so that I can come back to read this discussion.
  60. Free book.[ Go to top ]

    can i download this .pdf file? tell me please. thank.