简体   繁体   中英

Hibernate update entity not knowing primary key

I have a US entity which has a id that is primary key and a userId and a ServiceId that these last two together they too are unique. now I have a userId and a serviceId and I wanna update a US entity and I don't know the correct syntax using hibernate to do that. Would any one help me, please... I've used annotation for entity mapping:

@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;

Try this:

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); 

That's it. Once the entity is loaded from DB, it's automatically attached to the current Session, so any change will be detected by the automatic dirty checking mechanism .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM