Spring,Java:将通用对象列表作为返回类型传递(Spring, Java : Passing Generic object List as return type)

我正在开发一个Spring-MVC应用程序,根据用户设置的模式,我必须返回一个Object1或Object2的List。 理想情况下,我可以创建两个控制器方法并适当地发送List,但我想知道是否有任何方法,我可以在该Controller方法中发送任何类型的List。

控制器方法:

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/findnotebydays/{days}/{canvasid}/{mode}")
public @ResponseBody List<Inotes> findNotesByDays(@PathVariable("days")int days, @PathVariable("canvasid")int canvasid,
                                                  @PathVariable("mode")boolean mode ){

    if(!mode){
        return this.groupNotesService.findGroupNotesByDays(days,canvasid);
    } else {
        return this.notesService.findNotesByDays(days,canvasid);
    }
}

基本上,如果mode为false,我想返回List<GroupNotes> ,如果mode为true,我想返回List<Notes> 。 我的天真的方法,我认为我可以说它是一个对象并返回,但似乎不起作用。 请让我知道我能做些什么。 非常感谢。 :-)

更新

GroupNotes模型类:

@Entity
@Table(name="groupnotes")
public class GroupNotes implements Inotes{

  @Id
    @Column(name="mnoteid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "mnote_gen")
    @SequenceGenerator(name = "mnote_gen",sequenceName = "mnote_seq")
    @org.hibernate.annotations.Index(name = "mnoticesidindex")
    private int mnoticesid;

    @Column(name = "mnotetext")
    private String mnotetext;
//Other variables, getters, setters ignored
}

Notes模型类:

@Entity
@Table(name="note")
public class Notes implements Inotes{

    @Id
    @Column(name="noteid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "note_gen")
    @SequenceGenerator(name = "note_gen",sequenceName = "note_seq")
    @org.hibernate.annotations.Index(name = "noteidindex")
    private int noticesid;

    @Column(name = "notetext")
    private String notetext;
//Other variables, getters, setters ignored
}

界面信息:

package com.journaldev.spring.model;


public interface Inotes {
}

I am working on a Spring-MVC application in which depending upon the mode set by the user, I have to return a List of either Object1 or Object2. Ideally, I can create two controller methods and send the List appropriately, but I would like to know is there any way, I can send any type of List in that Controller method.

Controller method :

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/findnotebydays/{days}/{canvasid}/{mode}")
public @ResponseBody List<Inotes> findNotesByDays(@PathVariable("days")int days, @PathVariable("canvasid")int canvasid,
                                                  @PathVariable("mode")boolean mode ){

    if(!mode){
        return this.groupNotesService.findGroupNotesByDays(days,canvasid);
    } else {
        return this.notesService.findNotesByDays(days,canvasid);
    }
}

Basically, if mode is false, I want to return List<GroupNotes> and if mode is true, I would like to return List<Notes>. My naive approach that I thought I can just say it is an Object and return, but doesn't seem to work. Kindly let me know what I can do. Thanks a lot. :-)

Update

GroupNotes model class :

@Entity
@Table(name="groupnotes")
public class GroupNotes implements Inotes{

  @Id
    @Column(name="mnoteid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "mnote_gen")
    @SequenceGenerator(name = "mnote_gen",sequenceName = "mnote_seq")
    @org.hibernate.annotations.Index(name = "mnoticesidindex")
    private int mnoticesid;

    @Column(name = "mnotetext")
    private String mnotetext;
//Other variables, getters, setters ignored
}

Notes model class :

@Entity
@Table(name="note")
public class Notes implements Inotes{

    @Id
    @Column(name="noteid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "note_gen")
    @SequenceGenerator(name = "note_gen",sequenceName = "note_seq")
    @org.hibernate.annotations.Index(name = "noteidindex")
    private int noticesid;

    @Column(name = "notetext")
    private String notetext;
//Other variables, getters, setters ignored
}

Interface Inotes :

package com.journaldev.spring.model;


public interface Inotes {
}

原文:https://stackoverflow.com/questions/30868002
2023-03-14 10:03

满意答案

这是一个优雅,Pythonic的做法:

>>> array([[1,2,3],]*3)
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

[16]的问题似乎是转置对数组没有影响。 你可能想要一个矩阵:

>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
        [2],
        [3]])

Here's an elegant, Pythonic way to do it:

>>> array([[1,2,3],]*3)
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

the problem with [16] seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:

>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
        [2],
        [3]])

相关问答

更多

使用存储在向量中的行/列指示填充矩阵的最快方法(Fastest way to populate a matrix using row/column indicies stored in vectors)

这是一些解决方案。 不需要包裹。 1)表 table(vectorRows, vectorCols) 赠送: vectorCols vectorRows 1 2 3 1 0 1 0 2 1 0 2 3 1 0 0 请注意,如果有任何行或列没有条目,那么它将不会出现。 2)聚合 ag <- aggregate( Freq ~ ., data.frame(Freq = 1, vectorRows, vectorCols), ...

如何将行向量转换为Eigen中的列向量?(How to convert row vector to column vector in Eigen?)

transposeInPlace的文档说: 注意 如果矩阵不是正方形,那么*this必须是可调整大小的矩阵。 你需要你的类型有两个动态行和列: Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> 但是,这已经有一个typedef : MatrixXd 。 或者,如果您仍然需要编译时的大小,则可以使用tranpose而不是transposeInPlace为您提供新的转置矩阵,而不是修改当前的矩阵: typedef Eigen::Matrix<...

将第一行(列标题)写入向量(writing first row (column headers) to a vector)

所以,根据你提供的数据,我在这里提出了一个解决方案。 你说:“ 我需要从测试数据中提取客户数据并将其放入矩阵的第一列 - 这是我的主要问题 ”。 提取的方法是: colnames(wsratings)或dimnames(wsratings)[[2]] 。 一旦你有了这个向量(长度为320),你想“把它放到第一列”。 你要求一个cbind() ,但是你想绑定它的数据的长度包含43行。 你不能将它们绑定在一起,因为这两个元素的长度不一样或者是对方的倍数 。 假设你有完整的数据集和他们的长度匹配,那么代...

“克隆”行或列向量(“Cloning” row or column vectors)

这是一个优雅,Pythonic的做法: >>> array([[1,2,3],]*3) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) >>> array([[1,2,3],]*3).transpose() array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) [16]的问题似乎是转置对数组没有影响。 你可能想要一个矩阵: >>> x = array([1,2,3]) >>> ...

获取向量中矩阵索引的列和行名称(Get column and row names of matrix indices in a vector)

使用arr.ind=TRUE参数, which函数已经提供了一个很好的接口来获取满足特定条件的矩阵的所有行和列索引。 与循环遍历每个矩阵元素相比,这更少打字并且更有效。 例如,如果你想获得矩阵等于5的所有索引,你可以使用: (idx <- which(mat == 5, arr.ind=TRUE)) # row col # R1 1 2 # R3 3 4 现在剩下的就是使用矩阵的行名和列名进行的简单查找: cbind(rownames(mat)[idx[,"row"]], ...

使用几个大向量过滤行(Filter rows with several large vectors)

这使用了cross join的概念,即笛卡尔积(所有排列)。 因此,您的数组会生成一个派生表(在内存中),其行数为x*y*z ,其中x,y,z是数组的大小。 如果提供了大小为3,4和5的数组,则派生表的行数将为3 * 4 * 5 = 60。 你提供的产生一行的数组匹配只有4 * 1 * 1 = 4 下面的东西7是你正在搜索的主表。 即使有大量数据, covering index应该使这个东西飞起来。 覆盖索引是这样的覆盖索引,其中所提供的信息是通过索引的b树扫描给出的,并且不需要读取数据页。 为什...

MATLAB使用行和列索引向量访问稀疏矩阵中的多个元素(MATLAB accessing multiple elements in sparse matrix using row and column index vectors)

我认为C = A .* (B~=0); 应该管用。 在两个稀疏矩阵的逐次乘法中只能访问非零,因此速度很快。 I think C = A .* (B~=0); should work. Only non-zeros will be accessed in the entrywise multiplication of two sparse matrices so it will be fast.

将一个热行向量的numpy数组转换为索引的列向量(Turn a numpy array of one hot row vectors into a column vector of indices)

更新 :要获得更快的解决方案,请参阅Divakar的答案。 您可以使用numpy数组的nonzero()方法 。 它返回的元组的第二个元素就是你想要的。 例如, In [56]: x Out[56]: array([[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0]]) In [57]: x.nonzero()[1] Out[57]: array([2,...

使用不同长度的字符向量构建数据框列?(Build column of data frame with character vectors of different length?)

如果要在某列的每一行中存储不同的矢量大小,则需要使用list ,问题(来自?data.frame ) 如果将列表或数据框或矩阵传递给data.frame,就好像每个组件或列都已作为单独的参数传递一样 因此,您需要将其包装到I中以保护您所需的结构,例如 df <- data.frame(first = 1:2, Second = I(list("A", c("B", "C")))) str(df) # 'data.frame': 2 obs. of 2 variables: # $ first ...

根据行和列索引向量分配新的矩阵值(assign new matrix values based on row and column index vectors)

sub2ind可以在这里帮助, A = zeros(3,2) rows = [1 2 3]; cols = [1 2 1]; A(sub2ind(size(A),rows,cols))=1 A = 1 0 0 1 1 0 用一个向量'插入' b = [1,2,3]; A(sub2ind(size(A),rows,cols))=b A = 1 0 0 2 3 0 sub2ind c...

相关文章

更多

Object Oriented Programming

Some might also contend that inheritance should be ...

redis整合spring示例二—java操作redis(存对象及List)

在java操作redis中,咱们已经有了基本的java操作redis相关代码。下面继续 redis存放 ...

Solr Cache使用介绍及分析,包括LRUCache、filterCache、queryResultCache、documentCache、Generic Caches

本文将介绍Solr查询中涉及到的Cache使用及相关的实现。Solr查询的核心类就是SolrIndex ...

java List排序一

java List对象排序有多种方法,下面是其中两种 第一种方法,list中的对象实现Comparab ...

java通用返回对象

java通用返回对象返回对象通常包括是否成功、响应码、接口响应描述、响应实体几个属性

Python 列表(list)操作

列表就像java里的collection,所具有的特性也要比元组更多,更灵活,其character总结 ...

Guava学习笔记:复写的Object常用方法

  在Java中Object类是所有类的父类,其中有几个需要override的方法比如equals,h ...

hibernate list查询 报类型转换异常

查询方法如下: public List&lt;T&gt; find(String hql, Obje ...

ServletOutputStream cannot be resolved to a type

在使用jsp生成web图片时遇到这个问题,这是源代码中的一条语句,源代码可以执行,可是一将源码放入ec ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本