-->
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.  [ 18 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: Updating Object with collection
PostPosted: Mon Sep 05, 2005 9:43 am 
Newbie

Joined: Tue Aug 30, 2005 1:05 am
Posts: 11
Hi,
I have 2 POJO classes, Group and Customer. Group contains a collection of Customer objects. When I'm going to update a Group object, I can see following in the logs;

Code:
Hibernate: delete from customer_group where GroupId=?
Hibernate: insert into customer_group (GroupId, CustomerId) values (?, ?)
Hibernate: insert into customer_group (GroupId, CustomerId) values (?, ?)


customer_group table is the join table between Customer and Group. If a Group contains thousands of customers, then this process will be a huge overhead and probably take lot of memory and time to execute.

My code is :

Code:
Session session = HibernateUtil.getSession();
        Group groupLoded = (Group)session.createQuery("from Group " +
                "group where group.id = " +
                "'" + group.getStringId() )
                .uniqueResult();
        groupLoded.setCustomers(group.getCustomers());
        session.flush();


Note:
1) I only want to update customers values of the group object.
2) Group class contains lot of variables other than customer Set(it contains such as groupname, description, adddedDate etc..)
3) But I want to update customers only. If I use session.update(group), then it will update all the fields.

How can I solve this problem?

I really appreciate for any help.
Thank you.
thilinaa.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Sep 05, 2005 2:06 pm 
Pro
Pro

Joined: Fri Sep 02, 2005 4:21 am
Posts: 206
Location: Vienna
Hi,

Could you provide the mapping files you are using?

Erik


Top
 Profile  
 
 Post subject:
PostPosted: Mon Sep 05, 2005 11:42 pm 
Newbie

Joined: Tue Aug 30, 2005 1:05 am
Posts: 11
Mapping file is:

Code:
    <class name="Customer" table="Customers">       
        <id name="stringId" column="CustomerId" length="50"/>
        <property name="msisdn" column="MSISDN" length="20" />
        <property name="shortName" column="ShortName" length="200"/>
        <property name="fullName" column="FullName" length="200"/>
        <property name="email" column="Email" length="100" />
        <property name="status" column="Status" length="20" />
        <property name="lastModifiedDateTime" column="LastModifiedDateTime" type="timestamp"  />
        <set name="groups" >
            <key>
                <column name="CustomerId"/>               
            </key>
            <many-to-many class="Group" >
                <column name="GroupId"/>               
            </many-to-many>
        </set>
    </class>

    <class name="Group" table="Groups">       
        <id name="stringId" column="GroupId" length="50"/>
        <property name="groupName" column="GroupName" length="100"/>
        <property name="description" column="Description"/>
        <property name="lastModifiedDateTime" column="LastModifiedDateTime" type="timestamp"/>
        <set name="customers">
            <key>
                <column name="GroupId"/>               
            </key>
            <many-to-many class="Customer" >
                <column name="CustomerId"/>             
            </many-to-many>
        </set>
    </class>



Group class contains following attributes related and setter getter methods:

Code:
    private String stringId = "";
    private String groupName = "";
    private String description = "";
    private Date lastModifiedDateTime = null;
    private Set customers = new HashSet();



Customer class contains following attributes related and setter getter methods:


Code:
     private String stringId = "";
    private String msisdn = "";
    private String shortName = "";
    private String fullName = "";
    private String email = "";
    private String status = "";
    private Date lastModifiedDateTime = null;
    private Set groups = new HashSet();


Thank you.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 3:10 am 
Expert
Expert

Joined: Mon Jul 04, 2005 5:19 pm
Posts: 720
Take a look @ these two lines.

groupLoded.setCustomers(group.getCustomers());
session.flush();

groupLoded.setCustomers() says 'forget all current customers' (hence the delete) and 'here are the new customers' (hence the inserts) . session.flush says 'synchronize object graph w/ db' (do the delete and inserts) .

Change your java, not your mappings. If you "only want to update customers", call session.save(collectionofCustomers) .


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 3:52 am 
Newbie

Joined: Tue Aug 30, 2005 1:05 am
Posts: 11
Hi,

Quote:
groupLoded.setCustomers() says 'forget all current customers' (hence the delete) and 'here are the new customers' (hence the inserts) . session.flush says 'synchronize object graph w/ db' (do the delete and inserts) .


is correct. But according to the Hibernate API

Quote:
If you "only want to update customers", call session.save(collectionofCustomers) .


should be wrong, isn't it?

API says;
Session classes save method as
save(Object object)
Persist the given transient instance, first assigning a generated identifier.

Then we should have to pass a Group object to save method, not the collectionofcustomers as pointed out in u r previous post. Note that, collectionofcustomers is a attribute of the Group class.

I tried as follows;

Code:
session.update(group.getCustomers());


then it will throws following exception;

Code:
org.hibernate.MappingException: Unknown entity: java.util.HashSet
        at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:569)
        at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1086)
        at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:83)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)
        at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)
        at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)        at org.hibernate.impl.SessionImpl.save(SessionImpl.java:481)
        at org.hibernate.impl.SessionImpl.save(SessionImpl.java:476)
        at beyondm.alerta.hibernate.dao.GroupDAO.addCustomersToGroup(Unknown Source)



So any ideas................


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 3:58 am 
Expert
Expert

Joined: Mon Jul 04, 2005 5:19 pm
Posts: 720
thilinaa wrote:
should be wrong, isn't it?


It is wrong ... Heineken . You have the right idea though w/ the update invocation. Can't help you beyond that but you might want to make sure you aren't still calling Session.save ( you have SessionImpl.save in the stack trace ).


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 4:10 am 
Newbie

Joined: Tue Aug 30, 2005 1:05 am
Posts: 11
If I use session.update(group); then the same thing happen;

i can see following in the log;

Code:
Hibernate: update Groups set GroupName=?, Description=?, LastModifiedDateTime=? where GroupId=? and MarchantIdGroup=?
Hibernate: delete from customer_groups where GroupId=?
Hibernate: insert into customer_customers (GroupId,  CustomerId) values (?, ?)
Hibernate: insert into customer_customers (GroupId, CustomerId) values (?, ?)
................
.............


I want to see only the update of customer_groups table without deletion and lot of insersions.

In Hibernate is there any way to acheive this? I mean only with updates and without any delete and inserts......


Thank you.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 4:10 am 
Regular
Regular

Joined: Tue Oct 07, 2003 10:20 am
Posts: 77
If you've set the hashcode and equals methods on the Customer correctly, try the following code:

groupLoded.getCustomers().addAll(group.getCustomers());

This should only add the new unique customers to the HashSet (I'm assuming that your customers are unique). Then you can just rely on the flush synchronizing the data as before.

Personally I always make the setter methods for collections private, as it causes too many issues when people don't realise how Hibernate the way in which data is dirty-checked.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 5:22 am 
Pro
Pro

Joined: Fri Sep 02, 2005 4:21 am
Posts: 206
Location: Vienna
Hi,

thilinaa wrote:
I want to see only the update of customer_groups table without deletion and lot of insersions.

In Hibernate is there any way to acheive this? I mean only with updates and without any delete and inserts......

My opinion is that it isn't.

If your are adding new Customers to your group new entries have to be created in customer_groups - so there will be inserts.
If you remove existing associations between group and customer, there will be deletes.

My feeling is that you want something that is impossible - but maybe I misunderstood your requirements. If so: could you give a detailled example of what you expect?

Another remark: if you use batch updates (hibernate.jdbc.batch_size set to some positive value) and a decent database your inserts will be pretty fast (all will be done in one round-trip to the database) - we used this heavily in a projet and performance was good.

If it applies to your use case then the method sdknott suggests is the probably the best one.

Erik


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 06, 2005 11:35 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 12:50 pm
Posts: 5130
Location: Melbourne, Australia
It is not even conceptually possible to have updates when what we are talking about here is a Set. Think about it and you will understand why.


I suspect you have some other bug like broken equals/hashCode that is making you look for such a thing.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Sep 07, 2005 12:29 am 
Newbie

Joined: Tue Aug 30, 2005 1:05 am
Posts: 11
Yes Gavin, your correct.... but when comparing with JDBC database updates with Hibernate update, I can see the following difference.

Given data -
1) I have a group with set of customers already added (in customer_group table).
2) I have new collection (say X) of customers to add that group. This collection (X) may contain new customers as well as some of the already added customers. Also some customers may not in X which are already added in the database (as explain in (1))

3) I want to update customer_group table with collection X


With JDBC database update;
We only add additional customers from the collection X and remove already added customers (i.e explains in (1)) which are not in X

With Hibernate database Update:
It deletes all the data in the customer_group table and inserts all the data in colleaction X

Therfore Number of database trassactions are higher in Hibernate database update than JDBC update.

Initially, if the customer_group conatains thousands of records and, if I update with collection X then it will run lot of unnessasary database trasactions. This will reduce the speed of the application as well as performance. May be memory exception may arise......

Hope you will understand my explanation....

If Hibernate cant handle as JDBC update then, it may be a probleam with Hibernate, isn't it?

Any ideas???

Thank you.
thilinaa


Top
 Profile  
 
 Post subject:
PostPosted: Wed Sep 07, 2005 12:42 am 
Expert
Expert

Joined: Mon Jul 04, 2005 5:19 pm
Posts: 720
thilinaa wrote:
I have new collection (say X) of customers to add that group. This collection (X) may contain ... some of the already added customers.


There can't be duplicate elements in a Set.

I don't speak Australian but I'm pretty sure he means don't use a Set ;-)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Sep 07, 2005 12:52 am 
Pro
Pro

Joined: Fri Sep 02, 2005 4:21 am
Posts: 206
Location: Vienna
Hi thilinaa,

My feeling is that we're running in circles.

As far as I see you were given all the hints to do it correctly - because Hibernate can do what you expect as good as "pure" JDBC does.

I would strongly suggest that you construct the most simple use case (a unit test would be best from my point of view) illustrating your problem and provide all the code to reproduce it. Then we (at least I would be ready to take the time to do it) could post a solution (hopefully).

Would be less frustrating for all of us...

Erik


Top
 Profile  
 
 Post subject:
PostPosted: Fri Sep 09, 2005 1:01 am 
Newbie

Joined: Tue Aug 30, 2005 1:05 am
Posts: 11
Hi Erick,
Please accept my apologies for the delay in[/b] replying to the forum question dated Wed Sep 07, 2005. Now a days in Sri Lanka having FOSS - 2005 conference (see http://fosssl.org/)and we were bussy with that.

Details;
Hibernate Version : 3.0.5
Database : Mysql 4.0.18
Connection pooler : c3po
JDK version : 1.4.2_05
Tomcat verson : 4.1.24

I have posting my test classes here;

POJO classes (Group and Customer);

Code:
public class Group implements Serializable{

    private String stringId = "";
    private String groupName = "";
    private String description = "";
    private Date lastModifiedDateTime = null;
    private Set customers = new HashSet();

    public String getStringId() {
        return stringId;
    }

    public void setStringId(String stringId) {
        this.stringId = stringId;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getLastModifiedDateTime() {
        return lastModifiedDateTime;
    }

    public void setLastModifiedDateTime(Date lastModifiedDateTime) {
        this.lastModifiedDateTime = lastModifiedDateTime;
    }

    public Set getCustomers() {
        return customers;
    }

    public void setCustomers(Set customers) {
        this.customers = customers;
    }

    public void setCustomer(Customer customer) {
        customers.add(customer);
        //customer.setGroup(this);
    }

    public void removeCustomer(Customer customer) {
        customers.remove(customer);
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Group)) return false;

        final Group group = (Group) o;

        if (!stringId.equals(group.stringId)) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = stringId.hashCode();
        return result;
    }


}


Code:
public class Customer implements Serializable{

    private String stringId = "";
    private String msisdn = "";
    private String shortName = "";
    private String fullName = "";
    private String email = "";
    private String status = "";
    private Date lastModifiedDateTime = null;
    private Set groups = new HashSet();

    public String getStringId() {
        return stringId;
    }

    public void setStringId(String stringId) {
        this.stringId = stringId;
    }

    public String getMsisdn() {
        return msisdn;
    }

    public void setMsisdn(String msisdn) {
        this.msisdn = msisdn;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getLastModifiedDateTime() {
        return lastModifiedDateTime;
    }

    public void setLastModifiedDateTime(Date lastModifiedDateTime) {
        this.lastModifiedDateTime = lastModifiedDateTime;
    }

    public Set getGroups() {
        return groups;
    }

    public void setGroups(Set groups) {
        this.groups = groups;
    }

    public void setGroup(Group group) {
        groups.add(group);
        //group.setCustomer(this);
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Customer)) return false;

        final Customer customer = (Customer) o;

        if (!stringId.equals(customer.stringId)) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = stringId.hashCode();
        return result;
    }


}


DAO classes (GroupDAO and CustomerDAO);

Code:
public class GroupDAO {


    public GroupDAO() {
        HibernateUtil.beginTransaction();
    }

    public void makePersistent(Object object) throws Exception {
        try {
            Session session = HibernateUtil.getSession();
            session.save(object);
        } catch (HibernateException e) {
            throw e;
        }
    }

    public void makeTransient(Object object) throws Exception {
        try {
            HibernateUtil.getSession().delete(object);
            HibernateUtil.getSession().flush();
        } catch (HibernateException e) {
            throw e;
        }
    }

    public void addCustomersToGroup(Group group) throws Exception{
        System.out.println("Add Customers To Group ["+ group.getStringId() +"]");
        Session session = HibernateUtil.getSession();
        Group groupLoded = (Group)session.createCriteria(Group.class)
                .add(Expression.eq("id", group.getStringId()))
                .uniqueResult();
        groupLoded.setCustomers(group.getCustomers());
        session.flush();
    }


}


Code:
public class CustomerDAO {


    public CustomerDAO() {
        HibernateUtil.beginTransaction();
    }

    public void makePersistent(Object object) throws Exception {
        try {
            Session session = HibernateUtil.getSession();
            session.save(object);
        } catch (HibernateException e) {
            throw e;
        }
    }

    public void makeTransient(Object object) throws Exception {
        try {
            HibernateUtil.getSession().delete(object);
            HibernateUtil.getSession().flush();
        } catch (HibernateException e) {
            throw e;
        }
    }

}


Test class (TestData);

Code:
public class TestData {

    private Customer getCustomer(String id, String msisdn, String shortName, String fullName, String email,
                                 String status, Date lastModified){
        Customer customer = new Customer();
        customer.setStringId(id);
        customer.setMsisdn(msisdn);
        customer.setShortName(shortName);
        customer.setFullName(fullName);
        customer.setEmail(email);
        customer.setStatus(status);
        customer.setLastModifiedDateTime(lastModified);
        return customer;
    }

    private Group getGroup(String id, String name, String desc, Date lastModified){
        Group group = new Group();
        group.setStringId(id);
        group.setGroupName(name);
        group.setDescription(desc);
        group.setLastModifiedDateTime(lastModified);
        return group;
    }

    public static void main(String[] args) {
        TestData testData = new TestData();
        GroupDAO groupDAO = new GroupDAO();
        CustomerDAO customerDAO = new CustomerDAO();
        Group group = testData.getGroup("g1", "g1name", "g1desc", new Date());
        Customer customer1 = testData.getCustomer("c1", "111", "shn1", "fn1", "em1", "Enabled", new Date());
        Customer customer2 = testData.getCustomer("c2", "222", "shn2", "fn2", "em2", "Enabled", new Date());
        Customer customer3 = testData.getCustomer("c3", "333", "shn3", "fn3", "em3", "Enabled", new Date());
        try {
            groupDAO.makePersistent(group);
            customerDAO.makePersistent(customer1);
            customerDAO.makePersistent(customer2);
            customerDAO.makePersistent(customer3);

            Set groupSet = new HashSet();
            groupSet.add(group);
            customer3.setGroups(groupSet);

            Set customersSet = new HashSet();
            customersSet.add(customer3);
            group.setCustomers(customersSet);
            groupDAO.addCustomersToGroup(group);

            ///////////// group object update with customer4 object
            Customer customer4 = testData.getCustomer("c4", "444", "shn4", "fn4", "em4", "Enabled", new Date());
            Set groupSetNew = new HashSet();
            groupSetNew.add(group);
            customer4.setGroups(groupSetNew);

            Set customersSetNew = new HashSet();
            customersSetNew.add(customer4);
            customersSetNew.add(customer3);
            group.setCustomers(customersSetNew);
            customerDAO.makePersistent(customer4);
            groupDAO.addCustomersToGroup(group);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.commitTransaction();
            HibernateUtil.closeSession();
        }
    }

}


hbm.xml mapping fiel (merchant.hbm.xml);

Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="hibernate.persistance">

    <class name="Group" table="Groups">
        <id name="stringId" column="GroupId" length="50"/>
        <property name="groupName" column="GroupName" length="100"/>
        <property name="description" column="Description"/>
        <property name="lastModifiedDateTime" column="LastModifiedDateTime" type="timestamp"/>
        <set name="customers" table="group_customer" lazy="true" >
            <key>
                <column name="GroupId" not-null="true" />
            </key>
            <many-to-many class="Customer" >
                <column name="CustomerId" not-null="true" />
            </many-to-many>
        </set>
    </class>

    <class name="Customer" table="Customers">
        <id name="stringId" column="CustomerId" length="50"/>
        <property name="msisdn" column="MSISDN" length="20" />
        <property name="shortName" column="ShortName" length="200"/>
        <property name="fullName" column="FullName" length="200"/>
        <property name="email" column="Email" length="100" />
        <property name="status" column="Status" length="20" />
        <property name="lastModifiedDateTime" column="LastModifiedDateTime" type="timestamp"  />
        <set name="groups" table="group_customer" inverse="true" lazy="true"  >
            <key>
                <column name="CustomerId"/>
            </key>
            <many-to-many class="Group" >
                <column name="GroupId"/>
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>


Note:
1) HibernateUtill class - Uses standerd class which is find in the web
2) Mysql Dialect set as - hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
3) Uncommented out - hibernate.hbm2ddl.auto create

After running the TestData class, I can find the following log;

Code:
Initializing HibernateUtil.....
Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@1f66cff [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@1db05b2 [ acquireIncrement -> 2, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, idleConnectionTestPeriod -> 3000, initialPoolSize -> 2, maxIdleTime -> 5000, maxPoolSize -> 4, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 2, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@c9d92c [ description -> null, driverClass -> null, factoryClassLocation -> null, jdbcUrl -> jdbc:mysql://192.168.0.143:3306/TestUpdate, properties -> {user=******, password=******} ] , preferredTestQuery -> null, propertyCycle -> 300, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ] , factoryClassLocation -> null, numHelperThreads -> 3, poolOwnerIdentityToken -> 1f66cff ]
10:30:38,889  INFO SchemaExport:113 - Running hbm2ddl schema export
10:30:38,896  INFO SchemaExport:129 - exporting generated schema to database
Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@90832e [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@1947496 [ acquireIncrement -> 2, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, idleConnectionTestPeriod -> 3000, initialPoolSize -> 2, maxIdleTime -> 5000, maxPoolSize -> 4, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 2, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@8a548b [ description -> null, driverClass -> null, factoryClassLocation -> null, jdbcUrl -> jdbc:mysql://192.168.0.143:3306/TestUpdate, properties -> {user=******, password=******} ] , preferredTestQuery -> null, propertyCycle -> 300, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ] , factoryClassLocation -> null, numHelperThreads -> 3, poolOwnerIdentityToken -> 90832e ]
10:30:39,292 DEBUG SchemaExport:143 - alter table group_customer drop foreign key FK82C9999E5312A712
10:30:39,342 DEBUG SchemaExport:149 - Unsuccessful: alter table group_customer drop foreign key FK82C9999E5312A712
10:30:39,344 DEBUG SchemaExport:150 - General error: Can't create table './TestUpdate/#sql-d9d_418.frm' (errno: 150)
10:30:39,345 DEBUG SchemaExport:143 - alter table group_customer drop foreign key FK82C9999EA26055FE
10:30:39,349 DEBUG SchemaExport:149 - Unsuccessful: alter table group_customer drop foreign key FK82C9999EA26055FE
10:30:39,350 DEBUG SchemaExport:150 - General error: Can't create table './TestUpdate/#sql-d9d_418.frm' (errno: 150)
10:30:39,351 DEBUG SchemaExport:143 - drop table if exists Customers
10:30:39,355 DEBUG SchemaExport:143 - drop table if exists Groups
10:30:39,360 DEBUG SchemaExport:143 - drop table if exists group_customer
10:30:39,365 DEBUG SchemaExport:161 - create table Customers (
    CustomerId varchar(50) not null,
    MSISDN varchar(20),
    ShortName varchar(200),
    FullName varchar(200),
    Email varchar(100),
    Status varchar(20),
    LastModifiedDateTime datetime,
    primary key (CustomerId)
) type=InnoDB
10:30:39,370 DEBUG SchemaExport:161 - create table Groups (
    GroupId varchar(50) not null,
    GroupName varchar(100),
    Description varchar(255),
    LastModifiedDateTime datetime,
    primary key (GroupId)
) type=InnoDB
10:30:39,376 DEBUG SchemaExport:161 - create table group_customer (
    GroupId varchar(50) not null,
    CustomerId varchar(50) not null,
    primary key (GroupId, CustomerId)
) type=InnoDB
10:30:39,400 DEBUG SchemaExport:161 - alter table group_customer
    add index FK82C9999E5312A712 (GroupId),
    add constraint FK82C9999E5312A712
    foreign key (GroupId)
    references Groups (GroupId)
10:30:39,411 DEBUG SchemaExport:161 - alter table group_customer
    add index FK82C9999EA26055FE (CustomerId),
    add constraint FK82C9999EA26055FE
    foreign key (CustomerId)
    references Customers (CustomerId)
10:30:39,425  INFO SchemaExport:173 - schema export complete
Connection pooler successfully initiated............
Add Customers To Group [g1]
Hibernate: insert into Groups (GroupName, Description, LastModifiedDateTime, GroupId) values (?, ?, ?, ?)
10:30:39,917 DEBUG StringType:59 - binding 'g1name' to parameter: 1
10:30:39,919 DEBUG StringType:59 - binding 'g1desc' to parameter: 2
10:30:39,923 DEBUG TimestampType:59 - binding '2005-09-09 10:30:39' to parameter: 3
10:30:39,926 DEBUG StringType:59 - binding 'g1' to parameter: 4
Hibernate: insert into Customers (MSISDN, ShortName, FullName, Email, Status, LastModifiedDateTime, CustomerId) values (?, ?, ?, ?, ?, ?, ?)
10:30:39,933 DEBUG StringType:59 - binding '111' to parameter: 1
10:30:39,935 DEBUG StringType:59 - binding 'shn1' to parameter: 2
10:30:39,936 DEBUG StringType:59 - binding 'fn1' to parameter: 3
10:30:39,941 DEBUG StringType:59 - binding 'em1' to parameter: 4
10:30:39,942 DEBUG StringType:59 - binding 'Enabled' to parameter: 5
10:30:39,944 DEBUG TimestampType:59 - binding '2005-09-09 10:30:39' to parameter: 6
10:30:39,947 DEBUG StringType:59 - binding 'c1' to parameter: 7
Hibernate: insert into Customers (MSISDN, ShortName, FullName, Email, Status, LastModifiedDateTime, CustomerId) values (?, ?, ?, ?, ?, ?, ?)
10:30:39,950 DEBUG StringType:59 - binding '222' to parameter: 1
10:30:39,952 DEBUG StringType:59 - binding 'shn2' to parameter: 2
10:30:39,956 DEBUG StringType:59 - binding 'fn2' to parameter: 3
10:30:39,957 DEBUG StringType:59 - binding 'em2' to parameter: 4
10:30:39,959 DEBUG StringType:59 - binding 'Enabled' to parameter: 5
10:30:39,960 DEBUG TimestampType:59 - binding '2005-09-09 10:30:39' to parameter: 6
10:30:39,962 DEBUG StringType:59 - binding 'c2' to parameter: 7
Hibernate: insert into Customers (MSISDN, ShortName, FullName, Email, Status, LastModifiedDateTime, CustomerId) values (?, ?, ?, ?, ?, ?, ?)
10:30:39,966 DEBUG StringType:59 - binding '333' to parameter: 1
10:30:39,968 DEBUG StringType:59 - binding 'shn3' to parameter: 2
10:30:39,969 DEBUG StringType:59 - binding 'fn3' to parameter: 3
10:30:39,974 DEBUG StringType:59 - binding 'em3' to parameter: 4
10:30:39,976 DEBUG StringType:59 - binding 'Enabled' to parameter: 5
10:30:39,977 DEBUG TimestampType:59 - binding '2005-09-09 10:30:39' to parameter: 6
10:30:39,980 DEBUG StringType:59 - binding 'c3' to parameter: 7
Hibernate: insert into group_customer (GroupId, CustomerId) values (?, ?)
10:30:39,985 DEBUG StringType:59 - binding 'g1' to parameter: 1
10:30:39,989 DEBUG StringType:59 - binding 'c3' to parameter: 2
Hibernate: select this_.GroupId as GroupId0_, this_.GroupName as GroupName0_0_, this_.Description as Descript3_0_0_, this_.LastModifiedDateTime as LastModi4_0_0_ from Groups this_ where this_.GroupId=?
10:30:40,010 DEBUG StringType:59 - binding 'g1' to parameter: 1
10:30:40,041 DEBUG StringType:86 - returning 'g1' as column: GroupId0_
Add Customers To Group [g1]
Hibernate: select this_.GroupId as GroupId0_, this_.GroupName as GroupName0_0_, this_.Description as Descript3_0_0_, this_.LastModifiedDateTime as LastModi4_0_0_ from Groups this_ where this_.GroupId=?
10:30:40,106 DEBUG StringType:59 - binding 'g1' to parameter: 1
10:30:40,118 DEBUG StringType:86 - returning 'g1' as column: GroupId0_
Hibernate: insert into Customers (MSISDN, ShortName, FullName, Email, Status, LastModifiedDateTime, CustomerId) values (?, ?, ?, ?, ?, ?, ?)
10:30:40,148 DEBUG StringType:59 - binding '444' to parameter: 1
10:30:40,157 DEBUG StringType:59 - binding 'shn4' to parameter: 2
10:30:40,159 DEBUG StringType:59 - binding 'fn4' to parameter: 3
10:30:40,174 DEBUG StringType:59 - binding 'em4' to parameter: 4
10:30:40,175 DEBUG StringType:59 - binding 'Enabled' to parameter: 5
10:30:40,177 DEBUG TimestampType:59 - binding '2005-09-09 10:30:40' to parameter: 6
10:30:40,178 DEBUG StringType:59 - binding 'c4' to parameter: 7
[b]Hibernate: delete from group_customer where GroupId=?[/b]
10:30:40,181 DEBUG StringType:59 - binding 'g1' to parameter: 1
Hibernate: insert into group_customer (GroupId, CustomerId) values (?, ?)
10:30:40,184 DEBUG StringType:59 - binding 'g1' to parameter: 1
10:30:40,185 DEBUG StringType:59 - binding 'c3' to parameter: 2
Hibernate: insert into group_customer (GroupId, CustomerId) values (?, ?)
10:30:40,187 DEBUG StringType:59 - binding 'g1' to parameter: 1
10:30:40,204 DEBUG StringType:59 - binding 'c4' to parameter: 2
Process terminated with exit code 0



I have bold the Hibernate: delete from group_customer where GroupId=? in the logs; This means all the previous data in the group_customer table deleletd and inserts new data. Consern anout entries relatde to customer3. I don't want to delete that record from the group_customer table and i just want to insert only the customer4 in group_customer table, because customer3 already added.

But in here, Hibernate deleted customer3 records from the group_customer table and added it again.

If group_customer table contains thousands of data then, this will results the reduction of the speed as well as performance of the system when comparing with pure JDBC updates.

I thought that you understand my question clearly.

Any suggetions!!!!!!!!

Thank you
thilinaa.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Sep 09, 2005 3:54 am 
Regular
Regular

Joined: Tue Oct 07, 2003 10:20 am
Posts: 77
Having looked at your code there are a couple of issues.

Firstly, as far as I'm aware, Hibernate's dirty checking of Collections doesn't work as your expecting. It won't compare the contents of an object's original collection and compare them to the second collection to see which objects are new or have been deleted. You're going to have to set the data of your Set properties a bit more elegantly to achieve what you wish. In my experience, entirely replacing Collection properties on your beans is always a bad idea, you should always work with the bean's original collections and just add or delete objects from them.

For example, it might be worth creating a new method called setNewCustomerData on your Group objects which looks a bit like the following:
Code:
public void setNewCustomerData(Set newCustomerData)
{
    customers.retainAll(newCustomerData);
    customers.addAll(newCustomerData);
}


This will remove any Customers which no longer exist and add any new ones. However, this is reliant upon your equals and hashcode being correct for the Customer/Group objects.

On this note, using the objects identity in your equals/hashcode is generally a bad idea. It may be worth reading http://www.hibernate.org/109.html, and if possible separating your database identity from your business keys.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 18 posts ]  Go to page 1, 2  Next

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.