1

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;
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Ehphan
  • 537
  • 3
  • 7
  • 19
  • Can you provide the code of the class you want to map? – Jordi Castilla Dec 19 '14 at 10:32
  • Alright, but I've already mapped the entity and it's working correctly with other hibernate functions. I just wanna use this two value (userId, serviceId) instead of the primary key (id) to update an entity – Ehphan Dec 19 '14 at 10:36
  • You sholud use composite primary key. Read here about it http://stackoverflow.com/questions/3585034/how-to-map-a-composite-key-with-hibernate" – Cortwave Dec 19 '14 at 12:52

1 Answers1

1

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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911