Hibernate saveorupdate或merge用于保存/更新一对多关系对象

时间:2014-01-22 12:45:10

标签: java mysql spring hibernate google-app-engine

我正在使用Spring MVC 3和Hibernate开发一个应用程序。我有2个类User和TenancyDetails与父子关系。在编辑详细信息功能中,我们可以编辑类User的详细信息并动态添加classTenancyDetails项并保存更改。我正在使用hibernate saveorupdate()方法,而hibernate正在为类User创建一个新记录,它应该更新现有记录。这是我的代码。

模型类:

@Entity
@Table(name="tenancydetails")
public class TenancyDetails {

@Column(name="tenancyID")
@Id 
@GeneratedValue
private int tenancyId;  

@Column(name="landlordName")
@NotNull
private String landlordName;

@Column(name="landLordEmail") 
@NotNull
private String landlordEmail;

@Column(name="fromDate") 
@NotNull
private Date fromDate;

@Column(name="toDate")
@NotNull
private Date toDate;

@Column(name="location") 
@NotNull
private String location;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="userId", nullable=false)
private User user;

@Transient 
protected Object[] jdoDetachedState; 

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public int getTenancyId() {
    return tenancyId;
}

public void setTenancyId(int tenancyId) {
    this.tenancyId = tenancyId;
}

public String getLandlordName() {
    return landlordName;
}

public void setLandlordName(String landlordName) {
    this.landlordName = landlordName;
}

public String getLandlordEmail() {
    return landlordEmail;
}

public void setLandlordEmail(String landlordEmail) {
    this.landlordEmail = landlordEmail;
}

public Date getFromDate() {
    return fromDate;
}

public void setFromDate(Date fromDate) {
    this.fromDate = fromDate;
}

public Date getToDate() {
    return toDate;
}

public void setToDate(Date toDate) {
    this.toDate = toDate;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}       
}

@Entity
@Table(name="User")
public class User {
@Column(name="userId")
@Id     
private int userId; 

@Column(name="name")
private String name;

@Column(name="emailId")
@NotEmpty(message = "Please enter your email id")
@Size(max = 50, message = "Email id can only be upto 50 characters long")
private String emailId;

@Column(name="password")
@NotEmpty(message = "Please enter your password")
@Size(max = 20, message = "Password can only be upto 20 characters long")
private String password;    

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@Cascade({org.hibernate.annotations.CascadeType.DELETE_ORPHAN,
    org.hibernate.annotations.CascadeType.PERSIST,
    org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinColumn(name="userId"/*, nullable=true*/)
@LazyCollection(LazyCollectionOption.FALSE)
private List<TenancyDetails> tenancyDetails = null;

public User(){
    tenancyDetails = new AutoPopulatingList<TenancyDetails>(TenancyDetails.class);
}

public List<TenancyDetails> getTenancyDetails() {
    return tenancyDetails;
}

public void addTenancyDetail(TenancyDetails tenancyDetail) {
    if (!tenancyDetails.contains(tenancyDetail)) {
        tenancyDetails.add(tenancyDetail);
    }
}

public void setTenancyDetails(List<TenancyDetails> tenancyDetails) {
    this.tenancyDetails = tenancyDetails;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}   

}

控制器:

@RequestMapping(value = "/Profile/{userId}",  method = RequestMethod.POST)
    public ModelAndView saveProfileDetails(@PathVariable int userId, Model model, HttpServletRequest request, HttpServletResponse response,
            HttpSession session, ModelMap modelMap, @ModelAttribute("user") User user) {            
        System.out.println("am in save");
        model.addAttribute("user", user);
        System.out.println(user.getPassword());
        System.out.println(user.getTenancyDetails().get(0).getUser().getUserId());
        System.out.println(model.containsAttribute("user"));        
        tenantRatingService.saveProfileDetails(user);
        return new ModelAndView("editProfile","user", user);
    }

DAO方法:

public void saveProfileDetails(User user){      
        System.out.println("inside the save profile method");
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        System.out.println("before save: " + user.getPassword());
        System.out.println("before save: " + user.getTenancyDetails().get(0).getUser().getUserId());        
        session.saveOrUpdate(user);
        transaction.commit();
        session.flush();
        System.out.println(user.getPassword());
    }

我还在mysql中将两个类的id字段设置为AUTO_INCREMENT字段。 是否存在一对多映射或我使用的@GeneratedValue存在问题?还是与saveorupdate()方法有关?在这种情况下我应该使用merge()吗?就在saveorupdate()语句之前,正确打印出现有userId的值!

有人可以让我知道我哪里出错吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

我不知道,在呈现表单时如何将user对象放在Model中,最终会出现在"/Profile/{userId}"的POST方法中。 id对象的user变为0。这就是saveOrUpdate方法再次保存user的原因。要验证它,您可以在进入saveProfileDetails方法之前添加以下行:

user.setUserId(userId);

您的问题将得到解决。

您也可以在@SessionAttributes("user")的{​​{1}}和"/Profile/{userId}"方法的拥有控制器之前添加GET来解决此问题。

另见: