【发布时间】:2015-06-04 11:08:35
【问题描述】:
我正在尝试以下休眠查询,但它总是给我一个错误的结果:
@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();
唯一的问题是我必须通过用户名中的用户名来获取它。
用户:
@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;
}
【问题讨论】:
-
该用户名实际上返回了 id 1 吗?尝试替换 jconcorrentes.users.username ?与 ConcorrentesId1
-
另外:ConcorrentesId 为 null 或 ConcorrentesId1 与:ConcorrentesId1 相同,因为 NULL 不等于 1,除非你想说 IS NOT NULL 但那会可能给你更少的行,这不是我猜的问题
-
@JeremyC。一次执行每个查询会给出预期的答案,但使用 or 条件将无法正常工作。是的,我已经检查过了
-
你能在问题中添加你的表定义,这样我就可以更好地了解你实际上想要做什么?
-
我明白你想说什么,但 jconcorrentes.users.username ?不返回 jconcorrentes 为 null 的值
标签: java mysql sql hibernate hql