欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解析JPA的视图查询问题

程序员文章站 2023-12-20 20:45:46
昨天晚上遇到一个需求,每天早上要生成一份报告给各个部门的leader。实现方式基本上确定为html格式的电子邮件。但是数据方面犯了难。原因在于数据库中存储的数据是跨表的,而...

昨天晚上遇到一个需求,每天早上要生成一份报告给各个部门的leader。实现方式基本上确定为html格式的电子邮件。但是数据方面犯了难。原因在于数据库中存储的数据是跨表的,而且还要做count统计,这样得到的结果就不是原生的mysql表,我用的又是jpa技术。我们知道,使用jpa第一步就是映射实体,每一张表就至少对应一个实体(力求严谨,因为联合主键时一张表会对应两个对象)。可是对于灵活的查询尤其是连接查询,并不存在一个真正的表与其对应,怎么样才能解决呢?来,我们来举个“栗子”

假设我们有两张表,一张学院表,一张学生表。学院表里存着学院id和学院名称,学生表里存着学生的基本信息,包括学号、学院id和学生姓名(其它较复杂的属性我们不看了),正如下面的建表语句所示:

复制代码 代码如下:

-- ----------------------------
-- table structure for `depts`
-- ----------------------------
drop table if exists `depts`;
create table `depts` (
  `deptid` int(11) unsigned not null auto_increment comment '学院id',
  `deptname` varchar(50) not null comment '学院名称',
  primary key (`deptid`)
) engine=innodb auto_increment=14 default charset=utf8;

-- ----------------------------
-- records of depts
-- ----------------------------
insert into `depts` values ('1', '哲学院');
insert into `depts` values ('2', '经济学院');
insert into `depts` values ('3', '法学院');
insert into `depts` values ('4', '教育学院');
insert into `depts` values ('5', '文学院');
insert into `depts` values ('6', '历史学院');
insert into `depts` values ('7', '理学院');
insert into `depts` values ('8', '工学院');
insert into `depts` values ('9', '农学院');
insert into `depts` values ('10', '医学院');
insert into `depts` values ('11', '军事学院');
insert into `depts` values ('12', '管理学院');
insert into `depts` values ('13', '艺术学院');


再建立一个学生表,再随便往里面插入点数据:
复制代码 代码如下:

-- ----------------------------
-- table structure for `students`
-- ----------------------------
drop table if exists `students`;
create table `students` (
  `stuno` bigint(20) unsigned not null auto_increment comment '学号 从1000开始',
  `deptid` int(10) unsigned not null comment '学院id',
  `stuname` varchar(50) not null comment '学生姓名',
  primary key (`stuno`),
  key `fk_deptid` (`deptid`),
  constraint `fk_deptid` foreign key (`deptid`) references `depts` (`deptid`) on update cascade
) engine=innodb auto_increment=1006 default charset=utf8;

-- ----------------------------
-- records of students
-- ----------------------------
insert into `students` values ('1000', '13', '鸟叔');
insert into `students` values ('1001', '7', '乔布斯');
insert into `students` values ('1002', '3', '阿汤哥');
insert into `students` values ('1003', '3', '施瓦辛格');
insert into `students` values ('1004', '2', '贝克汉姆');
insert into `students` values ('1005', '3', '让雷诺');


现在我们想统计一下各个学院都有多少学生。这个题目在我们学习sql的时候再简单不过了。两种实现方法:

使用group by和不使用group by:

复制代码 代码如下:

select b.deptid, b.deptname, count(*) as 'totalcount' from students a left join depts b on a.deptid=b.deptid group by b.deptid order by b.deptid;

使用group by之后,凡是没有对应学生记录的学院都没有显示出来(我不明白为什么。。。如果有人知道的话麻烦告诉我好吗?)
复制代码 代码如下:

+--------+--------------+------------+
| deptid | deptname     | totalcount |
+--------+--------------+------------+
|      2 | 经济学院     |          1 |
|      3 | 法学院       |          3 |
|      7 | 理学院       |          1 |
|     13 | 艺术学院     |          1 |
+--------+--------------+------------+

再来一个不使用group by的查询:
复制代码 代码如下:

select a.deptid, a.deptname, (select count(*) from students b where b.deptid=a.deptid) as 'totalcount' from depts a;

这次就完全显示出来了:
复制代码 代码如下:

+--------+--------------+------------+
| deptid | deptname     | totalcount |
+--------+--------------+------------+
|      1 | 哲学院       |          0 |
|      2 | 经济学院     |          1 |
|      3 | 法学院       |          3 |
|      4 | 教育学院     |          0 |
|      5 | 文学院       |          0 |
|      6 | 历史学院     |          0 |
|      7 | 理学院       |          1 |
|      8 | 工学院       |          0 |
|      9 | 农学院       |          0 |
|     10 | 医学院       |          0 |
|     11 | 军事学院     |          0 |
|     12 | 管理学院     |          0 |
|     13 | 艺术学院     |          1 |
+--------+--------------+------------+

至此,我们的sql写通了。但是怎么才能使用jpa来查询出一样的视图呢?

我们按照往常编码那样,从一个主要的实体操作服务中暴露出entitymanager来:

复制代码 代码如下:

package net.csdn.blog.chaijunkun.dao;

import javax.persistence.entitymanager;
import javax.persistence.persistencecontext;

import org.springframework.stereotype.service;

@service
public class objectdaoserviceimpl implements objectdaoservice {

 @persistencecontext
 private entitymanager entitymanager;

 @override
 public entitymanager getentitymanager(){
  return this.entitymanager;
 }

}


这样做的好处就是所有的数据操作都来源于同一个实体管理器。将来若部署发生变化,只改这一处注入就可以了。

然后我们还需要和以前一样构造两个表的实体类:

学院表的实体类:

复制代码 代码如下:

package net.csdn.blog.chaijunkun.pojo;

import java.io.serializable;

import javax.persistence.column;
import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.generationtype;
import javax.persistence.id;
import javax.persistence.table;

@entity
@table(name="depts")
public class depts implements serializable {

 /**
  *
  */
 private static final long serialversionuid = 3602227759878736655l;

 @id
 @generatedvalue(strategy= generationtype.auto)
 @column(name= "deptid")
 private integer deptid;

 @column(name= "deptname", length= 50, nullable= false)
 private string deptname;

 //getters and setters...
}


学生表的实体类:
复制代码 代码如下:

package net.csdn.blog.chaijunkun.pojo;

import java.io.serializable;

import javax.persistence.column;
import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.generationtype;
import javax.persistence.id;
import javax.persistence.joincolumn;
import javax.persistence.manytoone;
import javax.persistence.table;

@entity
@table(name= "students")
public class students implements serializable {

 /**
  *
  */
 private static final long serialversionuid = -5942212163629824609l;

 @id
 @generatedvalue(strategy= generationtype.auto)
 @column(name= "stuno")
 private long stuno;

 @manytoone
 @joincolumn(name= "deptid", nullable= false)<span style="white-space: pre"> </span>
 private depts depts;

 @column(name= "stuname", length= 50, nullable= false)
 private string stuname;

 //getters and setters...

}


两个实体类都构造好了,我们接下来还要弄一个视图类,属性的类型完全由你想要的结构来构造。例如这个例子中我们要学院编号,学院名称和总人数。那么我们就这么定义:
复制代码 代码如下:

package net.csdn.blog.chaijunkun.pojo;

import java.io.serializable;

public class report implements serializable {

 /**
  *
  */
 private static final long serialversionuid = 4497500574990765498l;

 private integer deptid;

 private string deptname;

 private integer totalcount;

 public report(){};

 public report(integer deptid, string deptname, integer totalcount) {
  this.deptid = deptid;
  this.deptname = deptname;
  this.totalcount = totalcount;
 }

 //getters and setters...

}


可以说,视图对象的定义比实体定义还要简单,不需要注解,不需要映射(以上代码为了减少代码量均省去了各属性的get和set方法,请自行添加)。但是唯一不同的是我们需要额外构造一个带有字段初始化的构造函数。并且还不能覆盖默认的无参构造函数。然后我们就开始进入真正的查询了(作为视图来讲,sql规范中是不允许修改数据的。因此,视图仅有select特性。这也是为什么很多人使用jpa想通过实体映射数据库内建视图的方式进行查询,却始终映射不成功的症结所在。
复制代码 代码如下:

package net.csdn.blog.chaijunkun.dao;

import java.util.list;

import javax.annotation.resource;
import javax.persistence.entitymanager;
import javax.persistence.typedquery;

import org.springframework.stereotype.service;

import net.csdn.blog.chaijunkun.pojo.depts;
import net.csdn.blog.chaijunkun.pojo.report;
import net.csdn.blog.chaijunkun.pojo.students;

@service
public class reportserviceimpl implements reportservice {

 @resource
 private objectdaoservice objectdaoservice;

 @override
 public list<report> getreport() {
  string jpql= string.format("select new %3$s(a.deptid, a.deptname, (select count(*) from %2$s b where b.deptid= a.deptid) as totalcount) from %1$s a",
    depts.class.getname(),
    students.class.getname(),
    report.class.getname());

  entitymanager entitymanager= objectdaoservice.getentitymanager();
  //建立有类型的查询
  typedquery<report> reporttypedquery= entitymanager.createquery(jpql, report.class);
  //另外有详细查询条件的在jpql中留出参数位置来(?1 ?2 ?3....),然后在这设置
  //reporttypedquery.setparameter(1, params);
  list<report> reports= reporttypedquery.getresultlist();
  return reports;
 }

}


在上面的代码中我们构造了jpql中的视图查询语句。最重要的就是要在最初的select后面new出新的对象。然后把我们查询到的结果通过视图对象的构造函数灌入各个属性。由统计生成的字段最好用as重命名结果以保持和视图对象属性名称相同。这样,我们就得到了视图数据。接下来就去尝试遍历这个list吧,操作非常方便。

另外,向大家推荐一本书——apress出版社出版的《pro jpa 2 mastering the java trade persistence api》,这本书详细介绍了jpa的相关技术,非常实用。

上一篇:

下一篇: