我有一个实体UserCredentials
,其中包含另外两个实体MobileUser
和Owner
。
UserCredentials
有一个SESSION_ID
应该返回给我UserCredentials.id
,以便我可以在MobileUser
和/或Owner
上设置约束:
get owner
where
owner.userCredentials.id == userCredentials.getIdBySessionId(sessionId)
但我完全被困在这里:
private long getOwnerId(Session session) throws NotFoundException {
HttpServletRequest httpRequest = getThreadLocalRequest();
String sessionId = httpRequest.getSession().getId();
if(session.getTransaction().isActive() == false) {
session.beginTransaction();
}
Criteria cr = session.createCriteria(UserCredentials.class);
// HOW TO DO SOMETHING LIKE DESCRIBED ABOVE?
@SuppressWarnings("unchecked")
List<UserCredentials> credentials = cr.list();
if(credentials.isEmpty()) {
throw new NotFoundException("Session id not found: " + sessionId);
}
logger.log(Level.DEBUG, "Retrieving owner id of userId: " + credentials.get(0).getUserId());
return credentials.get(0).getId();
}
有人能告诉我这是如何在&#34; 好&#34;方式 - 意思是如果没有必要,我不想多次获取。我想设置约束,然后调用criteria.list()
来获取所需的数据。
Owner.java
@Entity
@Table(name = "owner")
public class Owner implements Serializable {
private static final long serialVersionUID = 5932700164951552452L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@NotNull
@OneToOne(cascade = CascadeType.PERSIST)
private UserCredentials userCredentials;
// ...
}
UserCredentials.java
@Entity
@Table(name="user_credentials",
uniqueConstraints = { @UniqueConstraint(columnNames = { "USER_ID" })
, @UniqueConstraint(columnNames = { "SESSION_ID" })})
public class UserCredentials extends AbstractTimestampEntity implements Serializable {
private static final long serialVersionUID = -1749547554922053458L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name="SESSION_ID")
private String sessionId;
}