views:

123

answers:

1

I have a JPA entity that stores a fk id, a boolean and a timestamp:

@Entity
public class ChannelInUse implements Serializable {
  @Id
  @GeneratedValue
  private Long id;
  @ManyToOne
  @JoinColumn(nullable = false)
  private Channel channel;
  private boolean inUse = false;
  @Temporal(TemporalType.TIMESTAMP)
  private Date inUseAt = new Date();
  ...
 }

I want every new instance of this entity to result in a new row in the table. For whatever reason no matter what I do it always results in the row getting updated with a new timestamp value rather than creating a new row. Even tried to just use a native query to run an insert but channel's ID wasn't populated yet so I gave up on that. I've tried using an embedded id class consisting of channel.getId and inUseAt. My equals and hashcode for are:

 public boolean equals(Object obj){
  if(this == obj)
   return true;
  if(!(obj instanceof ChannelInUse))
   return false;
  ChannelInUse ciu = (ChannelInUse) obj;
  return ( (this.inUseAt == null ? ciu.inUseAt == null : this.inUseAt.equals(ciu.inUseAt)) 
    && (this.inUse == ciu.inUse) 
    && (this.channel == null ? ciu.channel == null : this.channel.equals(ciu.channel))
    );
 }
 /**
  * hashcode generated from at, channel and inUse properties. 
  */
 public int hashCode(){
  int hash = 1;
  hash = hash * 31 + (this.inUseAt == null ? 0 : this.inUseAt.hashCode());
  hash = hash * 31 + (this.channel == null ? 0 : this.channel.hashCode());
  if(inUse)
   hash = hash * 31 + 1;
  else
   hash = hash * 31 + 0;
  return hash;
 }
}

I've tried using hibernate's Entity annotation with mutable=false. I'm probably just not understanding what makes an entity unique or something. Hit the google pretty hard but can't figure this one out.

UPDATE: Adding persist code:

public void store(Map<String, String> params,

        Map<?, ?> values) throws Exception {
    VoiceInterface iface = (VoiceInterface) getStorageUnit(params);
    ALeafPort leafPort = getLeafPort(iface);
    SortedSet<Channel> channels = leafPort.getChannels();
    Iterator<Channel> it = channels.iterator();
    while(it.hasNext()){
        Channel c = it.next();
        ChannelInUse ciu = new ChannelInUse(c,
                           ((Boolean) values.get(c.getNumber())).booleanValue());   
        em.persist(ciu);
    }
}

getStorageUnit and getLeafPort look up the proper objects from storage (or creates them if they don't exist).

A: 

Yeah, should watch out for that hbm2ddl.auto=create property. Oops!

David Schlenk