gpt4 book ai didi

java - Hibernate 查询 "or condition"将不起作用

转载 作者:行者123 更新时间:2023-11-28 23:59:01 26 4
gpt4 key购买 nike

我正在尝试以下 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 个值,但这应该是“jconcorrentes.users.username <> ?”的结果

“jconcorrentes is null”的结果是 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();

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

用户:

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

最佳答案

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

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

关于java - Hibernate 查询 "or condition"将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com