2010-05-11 32 views
0

我有一个存储FK ID,一个布尔值和时间戳的JPA实体:存储JPA实体,其中只有时间戳的变化导致了更新,而不是插入(需要)

@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(); 
    ... 
} 

我希望每一个新实例该实体的结果导致表中的新行。无论出于什么原因,无论我做什么,总会导致行更新一个新的时间戳值,而不是创建一个新行。甚至试图只使用本地查询来运行插入,但通道的ID尚未填充,所以我放弃了这一点。我试过使用由channel.getId和inUseAt组成的嵌入式id类。我的等于和散列码为:

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; 
} 
} 

我试过使用hibernate的实体注释mutable = false。我可能只是不理解是什么使一个实体独特或什么。打谷歌很难,但无法弄清楚这一点。

更新:加入坚持代码:

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和getLeafPort从存储中查找适当的对象(或者创建他们,如果他们不存在)。

+0

'equals'和'hashCode'方法应该是不相关的。你正在创建两个实体('新的ChannelInUse()'),坚持每一个,第二个覆盖第一个?这听起来很奇怪。你能显示代码吗?已添加代码 – Henning 2010-05-11 16:52:51

+0

。我遍历一个Channel列表,然后为每个ChannelInUse对象在构造方法中使用它的当前状态,然后持久化。它会覆盖inUse和inUseAt,但它会为每个通道保留一行 - 就像它的治疗通道一样,即使它甚至不被用作主键或任何地方的复合键。是否因为我遍历了一个频道列表?不知何故? – 2010-05-11 21:19:18

回答

0

是的,应该注意那个hbm2ddl.auto =创建属性。哎呀!

相关问题