hibernate中部分函数学习

来源:互联网 发布:uu黑历史知乎 编辑:程序博客网 时间:2024/04/30 18:53

项目用的是hibernate, 要求dao中不能使用原生的sql, 要用hql, 不熟, 遇到了很多问题

1. 去重统计问题

需求: 查出某张表中某个字段的个数, 需要去重. 

hql : select count(DISTINCT s.teacher.id) from student as s

注意: distinct 去重, 与字段之间不能有 ( , 否则会报错

2. 将 null 值转为 0 

需求: 做统计时, 如果没有数据, 正常的sum将返回 null , 但是需要返回 0 , 此时可以用 coalesce() 函数

hql : select sum(s.score) from student s // 此时, 如果没查到数据, 返回 null 值

select coalesce(s.score, 0) from student s; // 经过此函数, 将返回 0 

coalesce() 函数返回的是第一个非 null 值, 例如 : coalesce(null, null ,1, 8, null)  将返回 1,

3. 最近遇到了一个问题, A, B 两个表关联, A 中的 column1 对应的是 B 中的 column2 , 但是在 B 中的 column2 中是用前缀的, 即当 A 的id 为 1 时, B 中存的是 str-1, 此时我用的函数是 concat, 具体 hql 如下:

select A.column1 from A, B where concat('str-', A.column1) = B.column2;

4. cast 函数, 用于转换数据类型

数据表中设计的日期存储是 int 类型, 格式: yyyyMMdd, 我想查出来的格式为 yyyy-MM-dd, 使用了这个函数, hql 如下

select cast( cast(a.createDate as date) as string) from A a; 因为直接转换为 date 的话, 在页面上显示的是 yyyy-MM-ddT00:00:00, 所以用了两次转换


5. hibernate 中使用 hql 执行 update 操作, 不能使用别名, 

update teacher set name = :name , age = :age, sex = :sex where id = :id;



6. hibernate 在使用 saveOrUpdate 方法时发现主对象和级联对象都删除了, 即在执行完 update 语句后, 发现都执行了 delete 语句.  当时使用的方法如下

Teacher 中有 Set<Student>

我的目的是更新与 teacher 关联的 student 的信息, 方法如下

teacher.getStudents().clear(); teacher.getStudents().add(student1); saveOrUpdate(teacher)

然后发现 teacher 和 student 都被删除.

  经检查发现是 student 的 @ManyToOne 注解中有 cascade=CascadeType.ALL, 而 teacher 的 @OneToMany 注解中有 mappedBy = teacher, 然后将两个去掉, 就正常了

参考文章: 


7. not in(data) 函数, 如果 data 中有 null 值, 则永远查不到数据 


0 0
原创粉丝点击