【问题标题】:Hibernate update entity not knowing primary key休眠更新实体不知道主键
【发布时间】:2015-02-18 06:23:09
【问题描述】:

我有一个美国实体,它的 id 是主键,还有一个 userId 和一个 ServiceId,最后两个一起它们也是唯一的。现在我有一个 userId 和一个 serviceId,我想更新一个美国实体,但我不知道使用 hibernate 的正确语法来做到这一点。有没有人能帮帮我,拜托... 我使用注解进行实体映射:

@Id
@Column(name = "USERSERVICE_ID")
@GeneratedValue
private Integer id;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "SERVICE_ID")
private Service service;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "SERVICE_SEND_TYPE_ID")
private ServiceSendType serviceSendType;

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

@Column(name = "USERSERVICE_UNSUBCTIMESTAMP")
private Date unsubscribeDate;

@Column(name = "USERSERVICE_SUBCTIMESTAMP")
private Date subscribeDate;

@Column(name = "USERSERVICE_ENABLED")
private Boolean enabled = false;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "SERVICE_USER_ID")
private User user;

【问题讨论】:

  • 能否提供你要映射的类的代码?
  • 好的,但是我已经映射了实体并且它与其他休眠功能一起正常工作。我只想使用这两个值(userId,serviceId)而不是主键(id)来更新实体
  • 你应该使用复合主键。阅读这里stackoverflow.com/questions/3585034/…"

标签: java hibernate jpa orm hibernate-criteria


【解决方案1】:

试试这个:

US entity = (US) session.createQuery("select s from US u where u.service.id = :serviceId and u.user.id = :userId")
.setParameter("serviceId", serviceId)
.setParameter("userId", userId)
.uniqueResult();
//update
entity.setEnabled(true); 

就是这样。从数据库加载实体后,它会自动附加到当前会话,因此automatic dirty checking mechanism 将检测到任何更改。

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 2020-02-16
    • 2013-07-24
    • 1970-01-01
    • 2018-10-24
    • 2013-06-18
    • 2019-06-22
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多