如何在Hibernate中为子表设置标准

时间:2015-06-15 23:59:48

标签: hibernate

我有一个实体UserCredentials,其中包含另外两个实体MobileUserOwner

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

0 个答案:

没有答案