`

Hibernate自动关联更新问题

阅读更多
Hibernate自动关联更新
最近项目一个一个问题

由hibernateTools生成的对象中已经做好关联关系

对象A:
package net.esj.model;
// Generated 2012-11-14 15:20:18 by Hibernate Tools 3.2.0.beta8


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import net.esj.basic.pojo.AbstractPojo;

import org.hibernate.annotations.GenericGenerator;

/**
* HdFormSubject generated by hbm2java
*/
@Entity
@Table(name="HD_FORM_SUBJECT"
    , uniqueConstraints = {  }
)
@org.hibernate.annotations.Entity(dynamicUpdate=true)
public class HdFormSubject extends AbstractPojo<String> implements java.io.Serializable {

    // Fields   

/**
     */
private String id;

/**
     */
private HdActForm hdActForm;

/**
     */
private String title;

/**
     */
private String parentId;

/**
     */
private Long index;

/**
     */
private Long rank;

private Boolean required;

private String typeCode;

/**
     */
private List<HdFormSubjectColumn> hdFormSubjectColumns = new ArrayList<HdFormSubjectColumn>();


     // Constructors

    /** default constructor */
    public HdFormSubject() {
    }

    /** full constructor */
    public HdFormSubject(HdActForm hdActForm, String title, String parentId, Long index, Long rank, List<HdFormSubjectColumn> hdFormSubjectColumns) {
       this.hdActForm = hdActForm;
       this.title = title;
       this.parentId = parentId;
       this.index = index;
       this.rank = rank;
       this.hdFormSubjectColumns = hdFormSubjectColumns;
    }
  
    // Property accessors
    /**      
     */
     @Id
    @Column(name="ID", unique=true, nullable=false, insertable=true, updatable=true)
    public String getId() {
        return this.id;
    }
   
    /**
     */ 
    public void setId(String id) {
        this.id = id;
    }
    /**      
     */
@ManyToOne(cascade={},
        fetch=FetchType.LAZY)
   
    @JoinColumn(name="ACT_ID", unique=false, nullable=true, insertable=true, updatable=true)
    public HdActForm getHdActForm() {
        return this.hdActForm;
    }
   
    /**
     */ 
    public void setHdActForm(HdActForm hdActForm) {
        this.hdActForm = hdActForm;
    }
    /**      
     */
   
    @Column(name="TITLE", unique=false, nullable=true, insertable=true, updatable=true, length=256)
    public String getTitle() {
        return this.title;
    }
   
    /**
     */ 
    public void setTitle(String title) {
        this.title = title;
    }
    /**      
     */
   
    @Column(name="PARENT_ID", unique=false, nullable=true, insertable=true, updatable=true)
    public String getParentId() {
        return this.parentId;
    }
   
    /**
     */ 
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
    /**      
     */
   
    @Column(name="\"INDEX\"", unique=false, nullable=true, insertable=true, updatable=true, precision=22, scale=0)
    public Long getIndex() {
        return this.index;
    }
   
    /**
     */ 
    public void setIndex(Long index) {
        this.index = index;
    }
    /**      
     */
   
    @Column(name="RANK", unique=false, nullable=true, insertable=true, updatable=true, precision=22, scale=0)
    public Long getRank() {
        return this.rank;
    }
   
    /**
     */ 
    public void setRank(Long rank) {
        this.rank = rank;
    }
    /**      
     */
    @OneToMany(cascade={CascadeType.ALL},targetEntity=net.esj.model.HdFormSubjectColumn.class, fetch=FetchType.LAZY, mappedBy="hdFormSubject")
    public List<HdFormSubjectColumn> getHdFormSubjectColumns() {
        return this.hdFormSubjectColumns;
    }
   
    /**
     */ 
    public void setHdFormSubjectColumns(List<HdFormSubjectColumn> hdFormSubjectColumns) {
        this.hdFormSubjectColumns = hdFormSubjectColumns;
    }

    @Column(name="REQUIRED", unique=false, nullable=true, insertable=true, updatable=true,  scale=0)
public Boolean getRequired() {
return required;
}

public void setRequired(Boolean required) {
this.required = required;
}

@Column(name="TYPE_CODE", unique=false, nullable=true, insertable=true, updatable=true)
public String getTypeCode() {
return typeCode;
}

public void setTypeCode(String typeCode) {
this.typeCode = typeCode;
}

public String genJsCode(){
StringBuilder sb = new StringBuilder();
sb.append("{").append("id:\"").append(id).append("\",")
.append("title:\"").append(title==null?"":title).append("\",")
.append("parentId:\"").append(parentId==null?"":parentId).append("\",")
.append("index:").append(index).append(",")
.append("rank:").append(rank==null?0:rank).append(",")
.append("required:").append(required==null?false:required).append(",")
.append("JS_FUNC:").append(typeCode==null?"":typeCode).append(",")
.append("typeCode:\"").append(typeCode==null?"":typeCode).append("\"}");

return sb.toString();
}


}


对象B:
package net.esj.model;
// Generated 2012-11-14 15:20:18 by Hibernate Tools 3.2.0.beta8


import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import net.esj.basic.pojo.AbstractPojo;

import org.hibernate.annotations.GenericGenerator;

/**
* HdFormSubjectColumn generated by hbm2java
*/
@Entity
@Table(name="HD_FORM_SUBJECT_COLUMN"
    , uniqueConstraints = {  }
)
@org.hibernate.annotations.Entity(dynamicUpdate=true)
public class HdFormSubjectColumn extends AbstractPojo<String> implements java.io.Serializable {

    // Fields   

/**
     */
private String id;

/**
     */
private HdFormSubject hdFormSubject;

/**
     */
private String title;

/**
     */
private String type;

/**
     */
private String typeExtra;

/**
     */
private String expressions;

/**
     */
private Long minLength;

/**
     */
private Long maxLength;

/**
     */
private Long index;

/**
     */
private Byte resultType;

/**
     */
private String defaultValue;

/**
     */
private String defaultMapping;

private String comments;

     // Constructors

    /** default constructor */
    public HdFormSubjectColumn() {
    }

    /** full constructor */
    public HdFormSubjectColumn(HdFormSubject hdFormSubject, String title, String type, String typeExtra, String expressions, Long minLength, Long maxLength, Long index, Byte resultType, String defaultValue, String defaultMapping) {
       this.hdFormSubject = hdFormSubject;
       this.title = title;
       this.type = type;
       this.typeExtra = typeExtra;
       this.expressions = expressions;
       this.minLength = minLength;
       this.maxLength = maxLength;
       this.index = index;
       this.resultType = resultType;
       this.defaultValue = defaultValue;
       this.defaultMapping = defaultMapping;
    }
  
    // Property accessors
    /**      
     */
    @Id
    @Column(name="ID", unique=true, nullable=false, insertable=true, updatable=true)
    public String getId() {
        return this.id;
    }
   
    /**
     */ 
    public void setId(String id) {
        this.id = id;
    }
    /**      
     */
@ManyToOne(cascade={javax.persistence.CascadeType.REMOVE},
        fetch=FetchType.LAZY)
    @JoinColumn(name="SUBJECT_ID", unique=false, nullable=true, insertable=true, updatable=true)
    public HdFormSubject getHdFormSubject() {
        return this.hdFormSubject;
    }
   
    /**
     */ 
    public void setHdFormSubject(HdFormSubject hdFormSubject) {
        this.hdFormSubject = hdFormSubject;
    }
    /**      
     */
   
    @Column(name="TITLE", unique=false, nullable=true, insertable=true, updatable=true, length=128)
    public String getTitle() {
        return this.title;
    }
   
    /**
     */ 
    public void setTitle(String title) {
        this.title = title;
    }
    /**      
     */
   
    @Column(name="TYPE", unique=false, nullable=true, insertable=true, updatable=true, length=64)
    public String getType() {
        return this.type;
    }
   
    /**
     */ 
    public void setType(String type) {
        this.type = type;
    }
    /**      
     */
   
    @Column(name="TYPE_EXTRA", unique=false, nullable=true, insertable=true, updatable=true, length=64)
    public String getTypeExtra() {
        return this.typeExtra;
    }
   
    /**
     */ 
    public void setTypeExtra(String typeExtra) {
        this.typeExtra = typeExtra;
    }
    /**      
     */
   
    @Column(name="EXPRESSIONS", unique=false, nullable=true, insertable=true, updatable=true, length=256)
    public String getExpressions() {
        return this.expressions;
    }
   
    /**
     */ 
    public void setExpressions(String expressions) {
        this.expressions = expressions;
    }
    /**      
     */
   
    @Column(name="MIN_LENGTH", unique=false, nullable=true, insertable=true, updatable=true, precision=0, scale=0)
    public Long getMinLength() {
        return this.minLength;
    }
   
    /**
     */ 
    public void setMinLength(Long minLength) {
        this.minLength = minLength;
    }
    /**      
     */
   
    @Column(name="MAX_LENGTH", unique=false, nullable=true, insertable=true, updatable=true, precision=0, scale=0)
    public Long getMaxLength() {
        return this.maxLength;
    }
   
    /**
     */ 
    public void setMaxLength(Long maxLength) {
        this.maxLength = maxLength;
    }
    /**      
     */
   
   
    /**      
     */
   
    @Column(name="\"INDEX\"", unique=false, nullable=true, insertable=true, updatable=true, precision=22, scale=0)
    public Long getIndex() {
        return this.index;
    }
   
    /**
     */ 
    public void setIndex(Long index) {
        this.index = index;
    }
    /**      
     */
   
    @Column(name="RESULT_TYPE", unique=false, nullable=true, insertable=true, updatable=true, precision=2, scale=0)
    public Byte getResultType() {
        return this.resultType;
    }
   
    /**
     */ 
    public void setResultType(Byte resultType) {
        this.resultType = resultType;
    }
    /**      
     */
   
    @Column(name="DEFAULT_VALUE", unique=false, nullable=true, insertable=true, updatable=true, length=256)
    public String getDefaultValue() {
        return this.defaultValue;
    }
   
    /**
     */ 
    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
    /**      
     */
   
    @Column(name="DEFAULT_MAPPING", unique=false, nullable=true, insertable=true, updatable=true, length=64)
    public String getDefaultMapping() {
        return this.defaultMapping;
    }
   
    /**
     */ 
    public void setDefaultMapping(String defaultMapping) {
        this.defaultMapping = defaultMapping;
    }

    @Column(name="COMMENTS", unique=false, nullable=true, insertable=true, updatable=true, length=512)
public String getComments() {
return comments;
}

public void setComments(String comments) {
this.comments = comments;
}

public String genJsCode(){
StringBuilder sb = new StringBuilder();
sb.append("{").append("id:\"").append(id).append("\",")
.append("title:\"").append(title==null?"":title).append("\",")
.append("type:\"").append(type==null?"":type).append("\",")
.append("typeExtra:\"").append(typeExtra==null?"":typeExtra).append("\",")
.append("expressions:\"").append(expressions==null?"":expressions).append("\",")
.append("minLength:").append(minLength==null?0:minLength).append(",")
.append("maxLength:").append(maxLength==null?0:maxLength).append(",")
.append("index:").append(index).append(",")
.append("resultType:").append(resultType==null?0:resultType).append(",")
.append("defaultValue:\"").append(defaultValue==null?"":defaultValue).append("\",")
.append("defaultMapping:\"").append(defaultMapping==null?"":defaultMapping).append("\",")
.append("comments:\"").append(comments==null?"":comments).append("\"}");
return sb.toString();
}
}


A中OneToMany关联:
    @OneToMany(cascade={CascadeType.ALL},targetEntity=net.esj.model.HdFormSubjectColumn.class, fetch=FetchType.LAZY, mappedBy="hdFormSubject")
    public List<HdFormSubjectColumn> getHdFormSubjectColumns() {
        return this.hdFormSubjectColumns;
    }
   
当CascadeType.ALL是会自动更新数据

调用的时候:
for(HdFormSubject subject:subjects){
subject.setHdActForm(form);
save(subject);
for(HdFormSubjectColumn col : subject.getHdFormSubjectColumns()){
col.setHdFormSubject(subject);
save(col);
}
}

这时执行的结果:
Hibernate: select hdformsubj_.ID, hdformsubj_.TYPE as TYPE126_, hdformsubj_.DEFAULT_VALUE as DEFAULT3_126_, hdformsubj_."INDEX" as INDEX4_126_, hdformsubj_.MIN_LENGTH as MIN5_126_, hdformsubj_.MAX_LENGTH as MAX6_126_, hdformsubj_.TITLE as TITLE126_, hdformsubj_.COMMENTS as COMMENTS126_, hdformsubj_.SUBJECT_ID as SUBJECT13_126_, hdformsubj_.TYPE_EXTRA as TYPE9_126_, hdformsubj_.EXPRESSIONS as EXPRESS10_126_, hdformsubj_.RESULT_TYPE as RESULT11_126_, hdformsubj_.DEFAULT_MAPPING as DEFAULT12_126_ from HD_FORM_SUBJECT_COLUMN hdformsubj_ where hdformsubj_.ID=?
Hibernate: select hdformsubj_.ID, hdformsubj_.TYPE_CODE as TYPE2_125_, hdformsubj_."INDEX" as INDEX3_125_, hdformsubj_.REQUIRED as REQUIRED125_, hdformsubj_.PARENT_ID as PARENT5_125_, hdformsubj_.TITLE as TITLE125_, hdformsubj_.RANK as RANK125_, hdformsubj_.ACT_ID as ACT8_125_ from HD_FORM_SUBJECT hdformsubj_ where hdformsubj_.ID=?
Hibernate: select hdformsubj_.ID, hdformsubj_.TYPE as TYPE126_, hdformsubj_.DEFAULT_VALUE as DEFAULT3_126_, hdformsubj_."INDEX" as INDEX4_126_, hdformsubj_.MIN_LENGTH as MIN5_126_, hdformsubj_.MAX_LENGTH as MAX6_126_, hdformsubj_.TITLE as TITLE126_, hdformsubj_.COMMENTS as COMMENTS126_, hdformsubj_.SUBJECT_ID as SUBJECT13_126_, hdformsubj_.TYPE_EXTRA as TYPE9_126_, hdformsubj_.EXPRESSIONS as EXPRESS10_126_, hdformsubj_.RESULT_TYPE as RESULT11_126_, hdformsubj_.DEFAULT_MAPPING as DEFAULT12_126_ from HD_FORM_SUBJECT_COLUMN hdformsubj_ where hdformsubj_.ID=?
Hibernate: select hdformsubj_.ID, hdformsubj_.TYPE as TYPE126_, hdformsubj_.DEFAULT_VALUE as DEFAULT3_126_, hdformsubj_."INDEX" as INDEX4_126_, hdformsubj_.MIN_LENGTH as MIN5_126_, hdformsubj_.MAX_LENGTH as MAX6_126_, hdformsubj_.TITLE as TITLE126_, hdformsubj_.COMMENTS as COMMENTS126_, hdformsubj_.SUBJECT_ID as SUBJECT13_126_, hdformsubj_.TYPE_EXTRA as TYPE9_126_, hdformsubj_.EXPRESSIONS as EXPRESS10_126_, hdformsubj_.RESULT_TYPE as RESULT11_126_, hdformsubj_.DEFAULT_MAPPING as DEFAULT12_126_ from HD_FORM_SUBJECT_COLUMN hdformsubj_ where hdformsubj_.ID=?
Hibernate: insert into HD_ACT_FORM (TITLE, COMMENTS, ARTICLE_ID, ID) values (?, ?, ?, ?)
Hibernate: insert into HD_FORM_SUBJECT (TYPE_CODE, "INDEX", REQUIRED, PARENT_ID, TITLE, RANK, ACT_ID, ID) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into HD_FORM_SUBJECT_COLUMN (TYPE, DEFAULT_VALUE, "INDEX", MIN_LENGTH, MAX_LENGTH, TITLE, COMMENTS, SUBJECT_ID, TYPE_EXTRA, EXPRESSIONS, RESULT_TYPE, DEFAULT_MAPPING, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into HD_FORM_SUBJECT_COLUMN (TYPE, DEFAULT_VALUE, "INDEX", MIN_LENGTH, MAX_LENGTH, TITLE, COMMENTS, SUBJECT_ID, TYPE_EXTRA, EXPRESSIONS, RESULT_TYPE, DEFAULT_MAPPING, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into HD_FORM_SUBJECT_COLUMN (TYPE, DEFAULT_VALUE, "INDEX", MIN_LENGTH, MAX_LENGTH, TITLE, COMMENTS, SUBJECT_ID, TYPE_EXTRA, EXPRESSIONS, RESULT_TYPE, DEFAULT_MAPPING, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update HD_FORM_SUBJECT_COLUMN set SUBJECT_ID=? where ID=?
Hibernate: update HD_FORM_SUBJECT_COLUMN set SUBJECT_ID=? where ID=?
Hibernate: update HD_FORM_SUBJECT_COLUMN set SUBJECT_ID=? where ID=?
看到会自动Update,而且把
for(HdFormSubjectColumn col : subject.getHdFormSubjectColumns()){
col.setHdFormSubject(subject);
save(col);
}
注释掉也没有用

将CascadeType.ALL去除才行
如果说带有级联会自动inert还可以理解,但是最后的update就百思不得其解了。。
而且该Update会把SUBJECT_ID设为NULL,即便hibernate自动更新也不应该是NULL啊
分享到:
评论

相关推荐

    Hibernate 关联关系解除

    在解除关联时,可以通过设置User的orders属性为null,然后保存User对象,让Hibernate自动处理数据库中的关系解除。 六、注意事项 在解除关联时,需要注意以下几点: 1. 数据库级约束:某些关联可能受到数据库级别的...

    hibernate多对多关联映射

    在开发过程中,IDE如IntelliJ IDEA和Eclipse提供了很好的Hibernate支持,可以自动生成关联映射代码和SQL语句,帮助我们更便捷地处理多对多关联。 总之,Hibernate的多对多关联映射是解决复杂关系数据库设计的关键...

    Hibernate实体关联速查表

    级联操作允许在操作一个实体时自动处理与之关联的其他实体。常见的级联类型包括:`ALL`(所有操作都级联)、`PERSIST`(保存)、`MERGE`(合并)、`REMOVE`(删除)、`REFRESH`(刷新)、`DETACH`(分离)等。 **六...

    如何解决hibernate自动更新实体类的问题共5页.pdf.zip

    1. **显式控制更新**:如果你不想让Hibernate自动更新实体,可以在修改完对象后,调用`Session.evict(entity)`方法将实体从Session缓存中移除,这样就不会触发自动更新。或者,如果不希望整个实体被更新,可以只更新...

    hibernate关联关系总结

    Hibernate关联关系是Java持久化框架Hibernate中的核心概念,它允许我们在数据库中建立对象之间的关系映射,以便在程序中操作对象时,可以自动处理与数据库的交互。本篇将深入探讨Hibernate的四种主要关联关系:一对...

    hibernate 关联表问题

    这个中间表通常不会在Java实体类中直接表示,而是由Hibernate自动管理。例如,对于“用户”和“角色”的多对多关联,中间表可能是`user_role`,包含`user_id`和`role_id`字段。 2. **配置映射文件** 在Hibernate的...

    hibernate自身关联一对多实例(树形结构)

    例如,添加一个新节点到树形结构中,可以先创建父节点和子节点对象,然后设置它们的引用关系,最后将父节点保存到数据库,Hibernate会自动处理关联关系。 ```java ParentEntity parent = new ParentEntity(); List...

    Hibernate自动生成持久化类和映射文件

    "Hibernate自动生成持久化类和映射文件"这个话题主要涉及如何利用myEclipse这款集成开发环境的反向工程功能,快速地根据数据库中的表结构生成对应的Hibernate配置文件、映射文件以及持久化类。下面将详细介绍这一...

    Hibernate单向关联代码示例

    在代码中,你可以创建`Department`对象,添加`Employee`对象到其`employees`列表中,然后通过Hibernate的Session对象保存`Department`,这将自动创建相关联的`Employee`记录。 ```java Session session = ...

    hibernate常用关联映射源码(很实用)

    该资源包括了hibernate开发中的常见关联映射的源代码,其中包括:one2one,one2many,many2many等,还有继承映射,inverse,fetch,cascade关键字的应用等,对初学者来说,是很实用的,难度适中,很好理解

    Hibernate多表关联配置及错误解决方法

    在SSH(Spring、Struts、Hibernate)框架中,MyEclipse可以自动生成实体类和映射文件。生成的实体类通常会实现`Serializable`接口,这是因为Hibernate在处理会话时需要用到序列化。如果你自己编写实体类,也要确保...

    Hibernate注解 关联关系映射注解.docx

    多对多的关联关系可以使用`@ManyToMany`注解,Hibernate会自动创建一个中间表来存储两个实体类之间的关联。如果需要自定义中间表的名称或字段,可以使用`@JoinTable`注解。在双向多对多关联中,依然需要`mappedBy`来...

    hibernate实现多对多关联关系源码

    这意味着添加或删除`User`的`Role`时,Hibernate会自动更新中间表。 4. **操作关联**:在业务逻辑中,可以通过以下方式添加、删除关联: ```java User user = new User(); user.setName("Alice"); entityManager....

    hibernate的关联映射

    级联操作允许我们在操作一个实体时,自动处理与其关联的其他实体。例如,当删除一个用户时,可以选择是否同时删除该用户的所有订单。常用的级联类型有`SAVE_UPDATE`、`PERSIST`、`REMOVE`、`REFRESH`和`ALL`。 **懒...

    hibernate自动生成

    Hibernate自动生成的DAO类通常会包含CRUD(创建、读取、更新、删除)的基本方法,如save()、get()、update()和delete()。这些方法内部调用了Hibernate的Session接口进行实际的数据操作。 4. **代码生成工具**:如...

    Hibernate一对多关联映射(注解)

    总结一下,Hibernate的一对多关联映射通过注解方式定义了对象间的关联关系,使得我们在编程时能够以面向对象的方式操作数据,而底层数据库的操作则由Hibernate自动完成。这种方式大大提高了开发效率,同时也降低了...

    Hibernate_关联关系映射配置

    级联操作允许我们在处理一个实体时自动处理与其关联的其他实体。例如,当我们删除一个父实体时,可以选择同时删除所有子实体。`CascadeType`枚举提供了多种级联选项,如`SAVE_UPDATE`, `DELETE`, `ALL`等。 总结: ...

    Hibernate 关联关系映射分类

    在深入探讨Hibernate关联关系映射分类之前,我们首先简要回顾一下Hibernate框架的基本概念。Hibernate是一种持久层框架,主要用于Java应用程序中的对象关系映射(ORM),它能够将面向对象的数据模型转换为数据库中的...

    Hibernate 映射文件自动生成

    5. **更新数据库表**:在生成映射文件后,还可以结合Hibernate的SchemaExport工具生成或更新数据库表结构。 这样的自动化过程可以帮助开发者节省大量时间,并且减少人为错误。在实际开发中,例如使用Eclipse或...

    hibernate代码自动生成

    2. 映射文件生成:为每个实体类生成对应的Hibernate映射文件(XML格式或使用注解),定义实体类与数据库表之间的映射关系,包括主键、字段类型、关联关系等。 3. DAO接口和实现类生成:自动生成数据访问接口和它的...

Global site tag (gtag.js) - Google Analytics