-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: Error on persisting objects in CaveatEmptor
PostPosted: Sat Jul 09, 2005 12:35 pm 
Beginner
Beginner

Joined: Tue Jun 28, 2005 8:51 pm
Posts: 20
Location: Bergamo, Italy
Hello i am trying to implement a simple version ov CaveatEmpter using Struts.
I' m tryng to study Using hibernate in a servlet engine cap 8.1.1(not read all the book)
The source of program on the hib site is too much complete and complex so i extracted 3 principal class and tryed to map them (Bid, User, Item).
I get an error on persisting objects: 8:19:54,750 ERROR SessionImpl: Could not synchronize database state with session

Can you help me understand what is the origin of this problem?

Tanks
Marco

ps: is there an example of source code with simple classes mappings needed to run book example? (first part)


Hibernate version:2 built in MyEclipse

Mapping documents:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<hibernate-mapping package="com.vano.hibernate.model" >

<class name="Bid"
table="BID">

<!-- Common id property. -->
<id name="id"
type="long"
column="BID_ID"
unsaved-value="null">
<generator class="native"/>
</id>

<!-- UserType for prices, length is precision of decimal field for DDL. -->
<property name="amount"
update="false"
type="java.math.BigDecimal"
column="AMOUNT" not-null="true" length="2"/>


<!-- We can't change the creation time, so map it with update="false". -->
<property name="created"
column="CREATED"
type="java.util.Date"
update="false"
not-null="true"/>

<!-- The other side of this bidirectional one-to-many association to item. -->
<many-to-one
name="item"
class="Item"
column="ITEM_ID"
update="false"
cascade="none"
not-null="true"
foreign-key="FK1_ITEM_ID"/>

<!-- The other side of this bidirectional one-to-many association to user. -->
<many-to-one
name="bidder"
class="User"
column="BIDDER_ID"
update="false"
cascade="none"
not-null="true"
foreign-key="FK2_BIDDER_ID"/>
</class>

</hibernate-mapping>


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!--

Mapping file for the Item class of CaveatEmptor.

An Item is the central entity of an auction. One interesting
aspect of this mapping is the <bag> used for the collection
of Bids. The Item Java class uses a List for this collection,
and Hibernate will order the collection on load by the
creation date of the bids.

Again, notice the 4000 character limit of Oracle VARCHAR
columns for the text description.

@author Christian Bauer <christian@hibernate.org>

-->
<hibernate-mapping package="com.vano.hibernate.model">

<class name="Item"
table="ITEM" >

<!-- Common id property. -->
<id name="id"
type="long"
column="ITEM_ID"
unsaved-value="null">
<generator class="native"/>
</id>

<!-- Name of the item is immutable. -->
<property name="name"
type="string"
column="NAME"
length="255"
not-null="true"
update="false"/>


<!-- Limit item description to 4000 characters, Oracle. -->
<property name="description"
type="string"
column="DESCRIPTION"
length="4000"
not-null="true"/>

<!-- UserTpe for prices, length is precision of decimal field for DDL. -->
<property name="initialPrice"
column ="INITIAL_PRICE" not-null="true" length="2"/>


<!-- We can't change the startDate. -->
<property name="startDate"
column="START_DATE"
type="java.util.Date"
update="false"
not-null="true"/>

<!-- We can't change the endDate. -->
<property name="endDate"
column="END_DATE"
type="java.util.Date"
update="false"
not-null="true"/>


<!-- Simple property. -->
<property name="approvalDateTime"
column="APPROVAL_DATETIME"
type="java.util.Date"
not-null="false"/>

<!-- We can't change the creation time, so map it with update="false". -->
<property name="created"
column="CREATED"
type="timestamp"
update="false"
not-null="true"/>


<!-- We can't change the seller. -->
<!-- <many-to-one name="seller"-->
<!-- class="User"-->
<!-- cascade="none"-->
<!-- column="SELLER_ID"-->
<!-- update="false"-->
<!-- not-null="true"-->
<!-- outer-join="false"-->
<!-- access="org.hibernate.auction.persistence.DirectSetAccessor"-->
<!-- foreign-key="FK2_SELLER_ID"/>-->

<!-- Mark the successful bid. -->
<!-- <many-to-one name="successfulBid"-->
<!-- class="Bid"-->
<!-- cascade="none"-->
<!-- column="SUCCESSFUL_BID_ID"-->
<!-- not-null="false"-->
<!-- outer-join="false"-->
<!-- foreign-key="FK3_SUCCESSFUL_BID_ID"/>-->

<!-- We use a one-to-many association to express the relationship
to a set of categories. There is an intermediate entity class,
CategorizedItem, which in fact makes this a many-to-many
association between Item and Category.
-->

<!-- un item puo avere tanti bit e un bid puo avere un solo item-->
<set name="bids" table="item_bids">
<key>
<column name="ITEM_ID" not-null="true" />
</key>
<one-to-many class="Bid" />
</set>

</class>

</hibernate-mapping
>

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<!--

Mapping file for the User class of CaveatEmptor.

A User is a versioned entity, with some special properties.
One is the username, it is immutable and unique. The
defaultBillingDetails property points to one of the
BillingDetails in the collection of all BillingDetails.

We never load any BillingDetails when a User is retrieved.

@author Christian Bauer <christian@hibernate.org>

-->
<hibernate-mapping package="com.vano.hibernate.model">

<class name="User"
table="USERS">

<id name="id"
type="long"
column="USER_ID"
unsaved-value="null">
<generator class="native"/>
</id>

<property name="firstname"
type="string"
column="FIRSTNAME"
length="255"
not-null="true"/>

<property name="lastname"
type="string"
column="LASTNAME"
length="255"
not-null="true"/>

<!-- We don't change the username, so map it with update="false".
This is an immutable property, it is also unique. -->
<property name="username"
type="string"
column="USERNAME"
length="16"
not-null="true"
unique="true"
update="false">
</property>

<!-- Password is a keyword in some databases, so we quote it. -->
<property name="password"
type="string"
column="`PASSWORD`"
length="12"
not-null="true"/>

<property name="email"
type="string"
column="EMAIL"
length="255"
not-null="true"/>

<property name="ranking"
type="int"
column="RANKING"
not-null="true"/>

<property name="admin"
type="boolean"
column="IS_ADMIN"
not-null="true"/>

<!-- We can't change the creation time, so map it with update="false". -->
<property name="created"
column="CREATED"
type="java.util.Date"
update="false"
not-null="true"/>


<!-- Mapping for Item association. -->
<set name="items"
cascade="none"
lazy="true"
inverse="true">
<key>
<column name="SELLER_ID" not-null="true"/>
</key>
<one-to-many class="Item"/>
</set>
<!---->


</class>

</hibernate-mapping>




Code between sessionFactory.openSession() and session.close():

public class ValutateBidAction extends Action {

// --------------------------------------------------------- Instance Variables

// --------------------------------------------------------- Methods

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

ValutateBidForm valutateBidForm = (ValutateBidForm) form;
//get from request, in this case from FormBean
Long itemId = Long.valueOf(valutateBidForm.getId());
Long userId = Long.valueOf(valutateBidForm.getUserid());
BigDecimal bidAmount =BigDecimal.valueOf(Long.valueOf(valutateBidForm.getAmount()));
try {
Session session = HibernateUtilBase.getSession();
System.out.println("Hello1");
Transaction tx = session.beginTransaction();
System.out.println("Hello2");
try {
// Load requested Item; pessimistic lock
//Item item = (Item) session.load(Item.class, itemId,LockMode.UPGRADE);
Item item = (Item) session.load(Item.class, itemId);
System.out.println("Hello3");
// Check auction still valid
if ( item.getEndDate().before( new Date() ) ) {
// Forward to error page
System.out.println("error1");
return (mapping.findForward("failure"));
}

// Check amount of Bid
System.out.println("Hello4");

Query q = session.createQuery("select max(b.amount)" + " from Bid b where b.item = :item");
System.out.println("Hello5");
q.setEntity("item", item);
System.out.println("Hello6");
BigDecimal maxBidAmount ;
maxBidAmount = (BigDecimal) q.uniqueResult();
if ( maxBidAmount == null)maxBidAmount =BigDecimal.valueOf(0);
System.out.println(maxBidAmount);
System.out.println("Helloxxx");
if (maxBidAmount.compareTo(bidAmount) > 0) {
// Forward to error page
System.out.println("error2");
return (mapping.findForward("failure"));
}

System.out.println("Hello8");

// Add new Bid to Item
User bidder = (User) session.load(User.class, userId);
System.out.println("Hello9");
Bid newBid = new Bid(bidAmount, item, bidder);
item.addBid(newBid);
System.out.println("Hello10");

// Place new Bid in scope for next page
tx.commit();

// Forward to Success.jsp page
return (mapping.findForward("success"));


} catch (HibernateException ex) {
if (tx != null) tx.rollback();
throw ex;
} finally {
session.close();
}
} catch (HibernateException ex) {return (mapping.findForward("failure"));}


}

}



Full stack trace of any exception that occurs:
Hello1
Hello2
Hibernate: select item0_.ITEM_ID as ITEM_ID0_, item0_.NAME as NAME0_, item0_.DESCRIPTION as DESCRIPT3_0_, item0_.INITIAL_PRICE as INITIAL_4_0_, item0_.START_DATE as START_DATE0_, item0_.END_DATE as END_DATE0_, item0_.APPROVAL_DATETIME as APPROVAL7_0_, item0_.CREATED as CREATED0_ from ITEM item0_ where item0_.ITEM_ID=?
Hibernate: select bids0_.ITEM_ID as ITEM_ID__, bids0_.BID_ID as BID_ID__, bids0_.BID_ID as BID_ID1_, bids0_.AMOUNT as AMOUNT1_, bids0_.CREATED as CREATED1_, bids0_.ITEM_ID as ITEM_ID1_, bids0_.BIDDER_ID as BIDDER_ID1_, user1_.USER_ID as USER_ID0_, user1_.FIRSTNAME as FIRSTNAME0_, user1_.LASTNAME as LASTNAME0_, user1_.USERNAME as USERNAME0_, user1_.`PASSWORD` as y5_0_, user1_.EMAIL as EMAIL0_, user1_.RANKING as RANKING0_, user1_.IS_ADMIN as IS_ADMIN0_, user1_.CREATED as CREATED0_ from BID bids0_ left outer join USERS user1_ on bids0_.BIDDER_ID=user1_.USER_ID where bids0_.ITEM_ID=?
Hello3
Hello4
Hello5
Hello6
Hibernate: select max(bid0_.AMOUNT) as x0_0_ from BID bid0_ where (bid0_.ITEM_ID=? )
0
Helloxxx
Hello8
Hibernate: select user0_.USER_ID as USER_ID0_, user0_.FIRSTNAME as FIRSTNAME0_, user0_.LASTNAME as LASTNAME0_, user0_.USERNAME as USERNAME0_, user0_.`PASSWORD` as y5_0_, user0_.EMAIL as EMAIL0_, user0_.RANKING as RANKING0_, user0_.IS_ADMIN as IS_ADMIN0_, user0_.CREATED as CREATED0_ from USERS user0_ where user0_.USER_ID=?
Hello9
Hello10
Hibernate: update BID set ITEM_ID=? where BID_ID=?
18:19:54,750 ERROR SessionImpl: Could not synchronize database state with session



Name and version of the database you are using:
MySql 4


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jul 10, 2005 11:11 am 
Beginner
Beginner

Joined: Tue Jun 28, 2005 8:51 pm
Posts: 20
Location: Bergamo, Italy
Oh yeah i solved it, the problem was only to add after
session.save(bidder);
the
session.save(newBid);

In the book it says that the Bid table will be saved using transitive persistence ( cascading from item to Bid).

How can i realize it?

tnks


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jul 10, 2005 1:45 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
You can use "cascade" options on the mapping. Read up on it in the book.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jul 10, 2005 2:32 pm 
Beginner
Beginner

Joined: Tue Jun 28, 2005 8:51 pm
Posts: 20
Location: Bergamo, Italy
Thank you,now works fine;)
i will ask you another last question:

i read about using filters, that are recomanded when using plain servlet programming.. on the book there are signals about frameworks and it say that using them probably no filter are required.
Do you know if in my case , using Struts, i can avoid filter ending my Action servlet in this way:

session.save(newBid);
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
// Place new Bid in scope for next page
// Forward to showSuccess.jsp page
return (mapping.findForward("success"));

Struts framework will manage problems that filters avoid?

tnks Again
Marco


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jul 10, 2005 4:17 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
The point of the interceptor-for-transaction-demarcation pattern is that you don't have to spread it throughout your code when all you do is S1/T1 per Http request/response (see the pictures in chapter 5 to understand that). So, find an interceptor that isn't a servlet filter, if you don't like to do it simple and easy, and use that then. Don't know if Struts has something native.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.