Hibernate查询"或条件"不会工作

时间:2015-06-04 11:08:36

标签: java mysql sql hibernate hql

我正在尝试以下hibernate查询,但它总是给我一个错误的结果:

    @SuppressWarnings("unchecked")
    @Override
    public List<Jcelulasmin> getAllOthers(int id, String username) {
        Session session = this.sessionFactory.getCurrentSession();
        List<Jcelulasmin> JcelulasList = session.createQuery("from Jcelulasmin where jgrelhas.id=? and (jconcorrentes is null or jconcorrentes.users.username <> ?) order by id").setParameter(0, id).setString(1, username).list();
        for(Jcelulasmin p : JcelulasList){
            logger.info("Jcelulas List::"+p);
        }
        return JcelulasList;
    }

此查询返回13个值,但这应该是&#34; jconcorrentes.users.username&lt;&gt;的结果。 ?&#34;

&#34; jconcorrentes的结果为空&#34;是47个值,所以我的查询应该返回47 + 13 = 60 ...

我试图实现以下实际返回60个值的SQL查询:

SELECT * FROM `jcelulas` WHERE GrelhasId=1 and (ConcorrentesId is null or ConcorrentesId<>1) 

ps:jconcorrentes.id为1所以sql和hql应该是相同的

表/实体定义:

@Entity
@Table(name = "jconcorrentes", catalog = "7jogos")
public class Jconcorrentes implements java.io.Serializable {

    private Integer id;
    ....
    private Users users;


@ManyToOne(fetch = FetchType.EAGER)
    @JsonBackReference
    @JoinColumn(name = "username", unique = true, nullable = false)
    public Users getUsers() {
        return this.users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

我尝试了以下内容并且确实有效:

session.createQuery("from Jcelulasmin where jgrelhas.id=? and (jconcorrentes is null or jconcorrentes <> 1) order by id").setParameter(0, id).list();

唯一的问题是我必须通过用户名中的用户名来获取它。

用户:

@Entity
@Table(name = "users", catalog = "7jogos", uniqueConstraints = @UniqueConstraint(columnNames = "username"))
public class Users implements java.io.Serializable {

@NotEmpty(message="Não se esqueça do Email")
@Email(message="Email Inválido")
private String username;
...
private Set<Jconcorrentes> jconcorrenteses = new HashSet<Jconcorrentes>(0);


@OneToMany(fetch = FetchType.EAGER, mappedBy = "users")
    public Set<Jconcorrentes> getJconcorrenteses() {
    return this.jconcorrenteses;
}

public void setJconcorrenteses(Set<Jconcorrentes> jconcorrenteses) {
    this.jconcorrenteses = jconcorrenteses;
}

2 个答案:

答案 0 :(得分:1)

您当前的查询转换为Jcelulasmin和jconcorrentes之间的内部联接(因为jconcorrentes.users.username),因此排除了空值。你必须明确地加入他们:

select j from Jcelulasmin j left join j.jconcorrentes jcon ...

答案 1 :(得分:0)

也许应该尝试jconcorrentes is null

,而不是jconcorrentes.id <> 1