更新jpa中实体的所有字段

时间:2015-10-21 08:26:11

标签: java hibernate jpa

我有两个实体用户和项目,他们有“一对多”关系,我想找到用户然后找到属于用户的特定项目,然后更新它,但我不能。 框架Struts2 + Hibernate。

@Entity (name = "User")
@Table (name = "users")
public class User implements Serializable{
@Id
@Column (name = "user_id", columnDefinition = "number")
@SequenceGenerator(name = "seq", sequenceName = "gen")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "seq")
private int id;

@Basic
@Column(name = "user_name", columnDefinition = "nvarchar2(20)")
private String userName;

@Basic
@Column(name = "password", columnDefinition ="nvarchar2(20)")
private String password;

@Basic
@Column(name = "create_date",columnDefinition = "date")
private Date creation_date;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private List<Project> projectses;

public List<Project> getProjectses() {
    return projectses;
}

public void setProjectses(List<Project> projectses) {
    this.projectses = projectses;
}

和项目实体

@Entity(name = "Project")
@Table(name = "project")
public class Project implements Serializable {
@Id
@Column(name = "project_id" , columnDefinition = "number")
@SequenceGenerator(name = "projectSeq", sequenceName = "projectGen")
@GeneratedValue(strategy = GenerationType.AUTO,generator = "projectSeq")
private int projectId;

@Basic
@Column(name = "project_name" , columnDefinition = "nvarchar2(20)")
private String projectName;

@Basic
@Column(name = "project_description" , columnDefinition = nvarchar2(20)")
private String projectDescription;

@Basic
@Column(name = "start_date",columnDefinition = "date")
private Date startDate;

@Basic
@Column(name = "due_date",columnDefinition = "date")
private Date dueDate;

@Basic
@Column(name = "project_status",columnDefinition = "nvarchar2(20)")
private String projectStatus;

@Basic
@Column(name = "project_amount",columnDefinition = "number(8)")
private int projectAmount;

2 个答案:

答案 0 :(得分:0)

<select id="provincias">
    <option value="130">A Coruña</option>
    <option value="131">Alava</option>
    <option value="132">Albacete</option>
</select>

获取用户对象,您将获得与该用户关联的项目集

更新您想要的数据: -

User u = (User)entityManager.createQuery(SELECT u FROM User u JOIN FETCH u.Project where u.id = :id).setParameter("id",your_userId).uniqueResult();

答案 1 :(得分:0)

考虑到三个更正,这可能会使您的代码表现良好:

  • 使用EntityManager#find()代替HQL按ID查找实体;

  • 只使用@Basic@Column中的一个(我更喜欢@Column),不需要同时使用这两个元素;

    < / LI>
  • 如果错误为“值对于列而言太长”,则可能是时候检查某些Project元素是否长于{{1中定义的20个字符}}?

检查columnDefinition个实体中字符串元素的长度,如果有超过20个字符,例如500,请修改Project这些元素,例如: G:

columnDefinition

我还建议在进行此类修改后删除表(允许JPA根据新定义创建新表)或手动修改其在DB中的定义。