Search code examples
hibernatecriteria

How Can I use Criteria with relational mapped objects?


I have mapped my relational bbdd tables to Java Objects.

@Entity
@Table(name = "user")
public class User implements Serializable{

// Another attributes...
@OneToOne
@JoinColumn(name = "id")
private UserAccount userAccount;

// Getters and setters...

}

@Entity
@Table(name = "user_account")
public class UserAccount implements Serializable{

@Id
@GenericGenerator(name = "generator", strategy = "foreign",
        parameters =
        @Parameter(name = "property", value = "user"))
@GeneratedValue(generator = "generator")
@Column(name = "user_id", unique = true, nullable = false)
private int user_id;
// Another attributes...

// Getters and setters...

}

I have one Criterion like this.

Criterion crit = Restrictions.and(
                Restrictions.like("userAccount.email", email),
                Restrictions.like("userAccount.password", MD5.crypt(password)));

But I get this error.

org.hibernate.QueryException: could not resolve property: User of: com.mypackage.entity.User

How can I do access to UserAccount.email from User through Criteria?


Solution

  • You have to create a new criteria for each join:

    Criteria criteria = session.createCriteria(User.class)
            .createCriteria("userAccount").add(Restrictions.and(
                    Restrictions.like("email", email),
                    Restrictions.like("password", MD5.crypt(password)));d