-->
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.  [ 2 posts ] 
Author Message
 Post subject: Help with simple association of entities [frustrating :( ]
PostPosted: Tue Jun 17, 2008 2:28 pm 
Newbie

Joined: Tue Jun 17, 2008 10:13 am
Posts: 1
Hi,

I understand simple questions aren't supposed to be asked without read the tutorials and such, but I have read through a lot of the examples, the hibernate docs and examples on blogs and such (The code I have used is modelled off of the caveatemptor example). It seems to be a non-issue wherever I look, yet it is escaping me... for 3 very frustrating days...

I saw another post that was talking about something similar but the resulting "solved" code didn't work for me either. The post talked about a Parent Child relationship... but I think what I am looking for is a reference or association as opposed to a one-to-one ownership type thing...

I basically just want a simple association between classes. I have two classes, one is called "CCR" and another is called "CCRType", CCR has a bunch of properties but it should have a column for ccr_type_id that would point to a corresponding CCRType. The table ccr_type will be fairly static. I.e. if I add more rows to the CCR table, I will only point to existing ids of ccr_type (I think this where I am not understand what annotation to use). Similarly, both CCR and CCRType need to point to the User class for fields such as "createdBy" and "updatedBy". It would be nice if I could do this without changing the class that is being pointed to, i.e. if I could point to the User class without it knowing about the CCR class (or the CCRType class).

the java code is:

CCR.java
Code:
package com.acs.scm.ccr.model;

// Imports
import org.appfuse.model.User;

import javax.persistence.*;

import org.hibernate.annotations.ForeignKey;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import java.util.Date;
import java.util.List;

/**
* Model for Change Control Request(CCR)
*
* @author Aditya Gaddam
* @version 0.1
*/
@Entity
public class CCR implements Comparable
{
   @Id
   @Column(name="ccr_id")
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   
   @ManyToOne
   @JoinColumn(name="ccr_type_id", insertable = false, updatable = false)
   @ForeignKey(name="ccr_type_id")
   private CCRType type;
   @Column(name="number")
   private Long number;
   @Column(name="title")
   private String title;
   @Column(name="description")
   private String description;
   @Column(name="open_date")
   private Date openDate;
   
   @Column(name="created_date")
   private Date createdDate;
   @ManyToOne
   @JoinColumn(name="id", insertable = false, updatable = false)
   @ForeignKey(name="created_by")
   private User createdBy;
   
   @Column(name="updated_date")
   private Date updatedDate;
   @ManyToOne
   @JoinColumn(name="id", insertable = false, updatable = false)
   @ForeignKey(name="updated_by")
   private User updatedBy;
   

   /**
     * @return the id
     */
    public Long getId()
    {
       return id;
    }

   /**
     * @return the type
     */
    public CCRType getType()
    {
       return type;
    }
   
    /**
     * @return the number
     */
    public Long getNumber()
    {
       return number;
    }

   /**
     * @return the title
     */
    public String getTitle()
    {
       return title;
    }

   /**
     * @return the description
     */
    public String getDescription()
    {
       return description;
    }

   /**
     * @return the openDate
     */
    public Date getOpenDate()
    {
       return openDate;
    }

   /**
     * @return the createdDate
     */
    public Date getCreatedDate()
    {
       return createdDate;
    }

   /**
     * @return the createdBy
     */
    public User getCreatedBy()
    {
       return createdBy;
    }

   /**
     * @return the updatedDate
     */
    public Date getUpdatedDate()
    {
       return updatedDate;
    }

   /**
     * @return the updatedBy
     */
    public User getUpdatedBy()
    {
       return updatedBy;
    }

   /**
     * @param id the id to set
     */
    public void setId(Long id)
    {
       this.id = id;
    }

   /**
     * @param type the type to set
     */
    public void setType(CCRType type)
    {
       this.type = type;
    }
   
    /**
     * @param number the number to set
     */
    public void setNumber(Long number)
    {
       this.number = number;
    }

   /**
     * @param title the title to set
     */
    public void setTitle(String title)
    {
       this.title = title;
    }

   /**
     * @param description the description to set
     */
    public void setDescription(String description)
    {
       this.description = description;
    }

   /**
     * @param openDate the openDate to set
     */
    public void setOpenDate(Date openDate)
    {
       this.openDate = openDate;
    }

   /**
     * @param createdDate the createdDate to set
     */
    public void setCreatedDate(Date createdDate)
    {
       this.createdDate = createdDate;
    }

   /**
     * @param createdBy the createdBy to set
     */
    public void setCreatedBy(User createdBy)
    {
       this.createdBy = createdBy;
    }

   /**
     * @param updatedDate the updatedDate to set
     */
    public void setUpdatedDate(Date updatedDate)
    {
       this.updatedDate = updatedDate;
    }

   /**
     * @param updatedBy the updatedBy to set
     */
    public void setUpdatedBy(User updatedBy)
    {
       this.updatedBy = updatedBy;
    }

   /**
     * @see java.lang.Comparable#compareTo(Object)
     */
    public int compareTo(Object object)
    {
      CCR myClass = (CCR) object;
      return new CompareToBuilder().
            append(this.title,          myClass.title).
            append(this.description,    myClass.description).
            append(this.openDate,       myClass.openDate).
            append(this.type,          myClass.type).toComparison();
    }

   /**
     * @see java.lang.Object#equals(Object)
     */
    public boolean equals(Object object)
    {
       if (!(object instanceof CCR))
        {
           return false;
        }
        CCR rhs = (CCR) object;
        return new EqualsBuilder().
            appendSuper(super.equals(object)).
            append(this.title,          rhs.title).
            append(this.description,    rhs.description).
            append(this.openDate,       rhs.openDate).
            append(this.type,          rhs.type).isEquals();
    }

   /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode()
    {
       return new HashCodeBuilder(-709614511, 254890457).
        appendSuper(super.hashCode()).
              append(this.title).
              append(this.description).
              append(this.openDate).
              append(this.type).
              toHashCode();
    }

   /**
     * @see java.lang.Object#toString()
     */
    public String toString()
    {
        return new ToStringBuilder(this).toString();
    }
}


CCRType.java
Code:
package com.acs.scm.ccr.model;

//Imports
import org.appfuse.model.User;

import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import java.util.Date;

/**
* Model for Change Control Request(CCR) type
*
* @author Aditya Gaddam
* @version 0.1
* @see CCRType
*
*/
@Entity
public class CCRType implements Comparable
{
   @Id
   @Column(name="ccr_id")
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   
   @Column(name="name")
   private String name;
   @Column(name="description")
   private String description;
   
   @Column(name="created_date")
   private Date createdDate;
   @ManyToOne
   @JoinColumn(name="id", insertable = false, updatable = false)
   @ForeignKey(name="created_by")
   private User createdBy;
   
   @Column(name="updated_date")
   private Date updatedDate;
   @ManyToOne
   @JoinColumn(name="id", insertable = false, updatable = false)
   @ForeignKey(name="updated_by")
   private User updatedBy;
   
   /**
     * @return the id
     */
    public Long getId()
    {
       return id;
    }

   /**
     * @return the name
     */
    public String getName()
    {
       return name;
    }

   /**
     * @return the description
     */
    public String getDescription()
    {
       return description;
    }

   /**
     * @return the createdDate

     */
    public Date getCreatedDate()
    {
       return createdDate;
    }

   /**
     * @return the createdBy
     */
    public User getCreatedBy()
    {
       return createdBy;
    }

   /**
     * @return the updatedDate
     */
    public Date getUpdatedDate()
    {
       return updatedDate;
    }

   /**
     * @return the updatedBy
     */
    public User getUpdatedBy()
    {
       return updatedBy;
    }

   /**
     * @param id the id to set
     */
    public void setId(Long id)
    {
       this.id = id;
    }

   /**
     * @param name the name to set
     */
    public void setName(String name)
    {
       this.name = name;
    }

   /**
     * @param description the description to set
     */
    public void setDescription(String description)
    {
       this.description = description;
    }
   
    /**
     * @param createdDate the createdDate to set
     */
    public void setCreatedDate(Date createdDate)
    {
       this.createdDate = createdDate;
    }

   /**
     * @param createdBy the createdBy to set
     */
    public void setCreatedBy(User createdBy)
    {
       this.createdBy = createdBy;
    }

   /**
     * @param updatedDate the updatedDate to set
     */
    public void setUpdatedDate(Date updatedDate)
    {
       this.updatedDate = updatedDate;
    }

   /**
     * @param updatedBy the updatedBy to set
     */
    public void setUpdatedBy(User updatedBy)
    {
       this.updatedBy = updatedBy;
    }

   /**
     * @see java.lang.Comparable#compareTo(Object)
     */
    public int compareTo(Object object)
    {
       CCRType myClass = (CCRType) object;
        return new CompareToBuilder().
              append(this.description, myClass.description).
              append(this.name, myClass.name).
              toComparison();
    }

   /**
     * @see java.lang.Object#equals(Object)
     */
    public boolean equals(Object object)
    {
       if (!(object instanceof CCRType))
        {
           return false;
        }
        CCRType rhs = (CCRType) object;
        return new EqualsBuilder().
              appendSuper(super.equals(object)).
              append(this.description, rhs.description).
              append(this.name, rhs.name).
              isEquals();
    }

   /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode()
    {
       return new HashCodeBuilder(-1067625411, -1495286683).appendSuper(
              super.hashCode()).
                append(this.description).
                append(this.name).
                toHashCode();
    }

   /**
     * @see java.lang.Object#toString()
     */
    public String toString()
    {
       return new ToStringBuilder(this).toString();
    }
   
}


The exception code below is from appfuse:gen. It seems to be trying to add rows to the User table when I add rows to the CCR... What I really want is for the CCR to just point a user who already exists (same with the CCRType)...

I know appfuse isn't related but I figured the SQL generated might give an idea as to what my annotations are doing as opposed to what they should be doing...

Are my annotations appropriate for my requirements?

Please help.

Thanks,
Aditya

Hibernate version:3

Mapping documents:Use annotations

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

Full stack trace of any exception that occurs:
Code:
+ Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'jetty'.
[INFO] ------------------------------------------------------------------------
[INFO] Building AppFuse Spring MVC Application
[INFO]    task-segment: [jetty:run]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing jetty:run
[INFO] [warpath:add-classes {execution: default}]
[INFO] [aspectj:compile {execution: default}]
[INFO] [native2ascii:native2ascii {execution: native2ascii-utf8}]
[INFO] [native2ascii:native2ascii {execution: native2ascii-8859_1}]
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] Preparing hibernate3:hbm2ddl
[WARNING] Removing: hbm2ddl from forked lifecycle, to prevent recursive invocation.
[INFO] [warpath:add-classes {execution: default}]
[INFO] [aspectj:compile {execution: default}]
[INFO] [native2ascii:native2ascii {execution: native2ascii-utf8}]
[INFO] [native2ascii:native2ascii {execution: native2ascii-8859_1}]
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[WARNING] POM for 'org.hibernate:jtidy:pom:r8-20060801:runtime' is invalid. It will be ignored for artifact resolution. Reason: Parse error reading POM. Reason: TEXT must be immediately followed by END_TAG and not START_TAG (position: START_TAG seen ...<licenses>\n\t\t\t<license>... @12:13)  for project org.hibernate:jtidy at C:\DOCUME~1\gaddama\.m2\repository\org\hibernate\jtidy\r8-20060801\jtidy-r8-20060801.pom
[INFO] [hibernate3:hbm2ddl {execution: default}]
[INFO] Configuration XML file loaded: file:/C:/Documents%20and%20Settings/gaddama/My%20Documents/Work/Java/AppFuse/CCRTracking/src/main/resources/hibernate.cfg.xml
[INFO] Configuration XML file loaded: file:/C:/Documents%20and%20Settings/gaddama/My%20Documents/Work/Java/AppFuse/CCRTracking/src/main/resources/hibernate.cfg.xml
[INFO] Configuration Properties file loaded: C:\Documents and Settings\gaddama\My Documents\Work\Java\AppFuse\CCRTracking\target\classes\jdbc.properties
alter table CCR drop foreign key ccr_type_id;
alter table CCR drop foreign key updated_by;
alter table CCRType drop foreign key updated_by;
alter table user_role drop foreign key FK143BF46A4FD90D75;
alter table user_role drop foreign key FK143BF46AF503D155;
drop table if exists CCR;
drop table if exists CCRType;
drop table if exists app_user;
drop table if exists role;
drop table if exists user_role;
create table CCR (ccr_id bigint not null auto_increment, created_date datetime, description varchar(255), number bigint, open_date datetime, title varchar(255), updated_date datetime, ccr_type_id bigint, id bigint, primary key (ccr_id)) ENGINE=InnoDB;
create table CCRType (ccr_id bigint not null auto_increment, created_date datetime, description varchar(255), name varchar(255), updated_date datetime, id bigint, primary key (ccr_id)) ENGINE=InnoDB;
create table app_user (id bigint not null auto_increment, account_expired bit not null, account_locked bit not null, address varchar(150), city varchar(50) not null, country varchar(100), postal_code varchar(15) not null, province varchar(100), credentials_expired bit not null, email varchar(255) not null unique, account_enabled bit, first_name varchar(50) not null, last_name varchar(50) not null, password varchar(255) not null, password_hint varchar(255), phone_number varchar(255), username varchar(50) not null unique, version integer, website varchar(255), primary key (id)) ENGINE=InnoDB;
[CCRTracking] ERROR [main] SchemaExport.create(274) | Unsuccessful: create table app_user (id bigint not null auto_increment, account_expired bit not null, account_locked bit not null, address varchar(150), city varchar(50) not null, country varchar(100), postal_code varchar(15) not null, province varchar(100), credentials_expired bit not null, email varchar(255) not null unique, account_enabled bit, first_name varchar(50) not null, last_name varchar(50) not null, password varchar(255) not null, password_hint varchar(255), phone_number varchar(255), username varchar(50) not null unique, version integer, website varchar(255), primary key (id)) ENGINE=InnoDB
[CCRTracking] ERROR [main] SchemaExport.create(275) | Table 'app_user' already exists
create table role (id bigint not null auto_increment, description varchar(64), name varchar(20), primary key (id)) ENGINE=InnoDB;
create table user_role (user_id bigint not null, role_id bigint not null, primary key (user_id, role_id)) ENGINE=InnoDB;
alter table CCR add index ccr_type_id (ccr_type_id), add constraint ccr_type_id foreign key (ccr_type_id) references CCRType (ccr_id);
alter table CCR add index updated_by (id), add constraint updated_by foreign key (id) references app_user (id);
alter table CCRType add index updated_by (id), add constraint updated_by foreign key (id) references app_user (id);
[CCRTracking] ERROR [main] SchemaExport.create(274) | Unsuccessful: alter table CCRType add index updated_by (id), add constraint updated_by foreign key (id) references app_user (id)
[CCRTracking] ERROR [main] SchemaExport.create(275) | Can't create table '.\ccrtracking\#sql-48c_30.frm' (errno: 121)
alter table user_role add index FK143BF46A4FD90D75 (role_id), add constraint FK143BF46A4FD90D75 foreign key (role_id) references role (id);
alter table user_role add index FK143BF46AF503D155 (user_id), add constraint FK143BF46AF503D155 foreign key (user_id) references app_user (id);
[WARNING] 5 errors occurred while performing <hbm2ddl>.
[ERROR] Error #1: java.sql.SQLException: Error on rename of '.\ccrtracking\ccr' to '.\ccrtracking\#sql2-48c-30' (errno: 152)
[ERROR] Error #1: java.sql.SQLException: Error on rename of '.\ccrtracking\ccrtype' to '.\ccrtracking\#sql2-48c-30' (errno: 152)
[ERROR] Error #1: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
[ERROR] Error #1: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'app_user' already exists
[ERROR] Error #1: java.sql.SQLException: Can't create table '.\ccrtracking\#sql-48c_30.frm' (errno: 121)
[INFO] [compiler:testCompile]
[INFO] Compiling 4 source files to C:\Documents and Settings\gaddama\My Documents\Work\Java\AppFuse\CCRTracking\target\test-classes
[INFO] [dbunit:operation {execution: test-compile}]
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error executing database operation: CLEAN_INSERT

Embedded error: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`ccrtracking/ccr_type`, CONSTRAINT `FK69170347EC2C75A1` FOREIGN KEY (`updated_by`) REFERENCES `app_user` (`id`))
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.lifecycle.LifecycleExecutionException: Error executing database operation: CLEAN_INSERT
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:583)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkProjectLifecycle(DefaultLifecycleExecutor.java:924)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.forkLifecycle(DefaultLifecycleExecutor.java:767)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:529)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:512)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:482)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
   at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
   at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
   at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
   at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
   at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
   at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error executing database operation: CLEAN_INSERT
   at org.codehaus.mojo.dbunit.OperationMojo.execute(OperationMojo.java:110)
   at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
   at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
   ... 20 more
Caused by: org.dbunit.DatabaseUnitException: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`ccrtracking/ccr_type`, CONSTRAINT `FK69170347EC2C75A1` FOREIGN KEY (`updated_by`) REFERENCES `app_user` (`id`))
   at org.dbunit.ant.Operation.execute(Operation.java:187)
   at org.codehaus.mojo.dbunit.OperationMojo.execute(OperationMojo.java:101)
   ... 22 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 52 seconds
[INFO] Finished at: Tue Jun 17 14:09:17 EDT 2008
[INFO] Final Memory: 31M/254M
[INFO] ------------------------------------------------------------------------


Name and version of the database you are using:MySQL 5

The generated SQL (show_sql=true):

Debug level Hibernate log excerpt:

Problems with Session and transaction handling?

Read this: http://hibernate.org/42.html[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jun 22, 2008 12:07 pm 
Hibernate Team
Hibernate Team

Joined: Thu Apr 05, 2007 5:52 am
Posts: 1689
Location: Sweden
Hi,

the classes CCR and CCRType[/i] look ok, but what's about the User class? How is this class mapped? It has to be an mapped entity as well. There seems already something going wrong in your schema export task. For example there is this message that app_user could not be created. I am not sure that the error occurs, because the app tries to update the user table, but rather that dbunit tries to do a clean insert, but it cannot write to the app_user table. What's about database and table permissions? Have you checked them?

I have never used appfuse so I don't know what it actually does. Maybe you could explain how the User class is mapped.

--Hardy


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 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.