EntityManager.merge()

时间:2015-05-01 18:12:24

标签: java hibernate jpa entitymanager hibernate-entitymanager

ReportDimensions.java:

package com.test.main.domain.resource;

import java.io.Serializable; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue;
import javax.persistence.Id; 
import javax.persistence.Table; 
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "report_dimensions") 
public class ReportDimensions implements Serializable {

    public ReportDimensions() {         
        super();    
    }

    public ReportDimensions(long userId, long reportId, String reportType) {
        super();        
        this.userId = userId;       
        this.reportType = reportType;       
    }


    public long getDimensionsId() {         
        return dimensionsId;    
    }

    public void setDimensionsId(long dimensionsId) {        
        this.dimensionsId = dimensionsId;   
    }

    public long getUserId() {       
        return userId;  
    }

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


    public String getReportType() {         
        return reportType;  
    }

    public void setReportType(String reportType) {      
        this.reportType =reportType;    
    }

    public int getWinWidth() {      
        return winWidth;    
    }

    public void setWinWidth(int winWidth) {         
        this.winWidth = winWidth;
    }

    public int getWinHeight() { 
        return winHeight;   
    }

    public void setWinHeight(int winHeight) {       
        this.winHeight = winHeight;     
    }

    @Id     
    @Column(name = "report_dimensions_id")  
    @GeneratedValue     
    private long dimensionsId;      

    @Column(name = "user_id")   
    @NotNull    
    private long userId;

    @Column(name = "report_type")   
    @NotNull    
    private String reportType;  

    @Column(name = "window_width")  
    @NotNull    
    private int winWidth; 

    @Column(name = "window_height")     
    @NotNull    
    private int winHeight;

    private static final long serialVersionUID = 1L;     
}

这是我的DAOImpl:

public void updateWindowSize(Long userId, String reportType, int width, int height)     {   
               ReportDimensions dimensions = entityManager.find(ReportDimensions.class, new   ReportDimensions(userId, reportType));

    if(dimensions == null) dimensions = new ReportDimensions(userId, reportType);       

 dimensions.setWinWidth(width);  dimensions.setWinHeight(height);

 entityManager.merge(dimensions);    }

在这里,我试图创建一条记录,如果不存在,则更新记录。 ReportDimensions的构造函数参数不具有主键,因为它是自动生成的。 根据EntityManager.find(arg1,arg2)的文档,我们必须使用主键作为第二个参数。我没有在任何时间检索自动生成的ID。我应该怎样做才能完成整个工作。

1 个答案:

答案 0 :(得分:0)

在使用Java构造对象时,确保“report_type”列的值不应为null。