如何序列化属性但不使用 spring 数据持久化它?

How to Serialize an Attribute but dont persist it using spring data?

我正在研究 spring 数据 + JPA,并创建了如下查询:

public interface GroupRepository extends JpaRepository<Group, Integer> {
    @Query("SELECT g.group, sum(ball) as sum from person ... group by ...", nativeQuery=false)
    List<Group> BallPerGroup();
}

return是:

sum    |     group
10     |   group 1
5      |   group 2
6      |   group 3

我有一个实体组:

public class Group{
    @Id @Genera...
    private Integer id;
    private String group;

    //getters and setter

}

我有一个实体人:

public class Person{
    @Id @Genera...
    private Integer id;
    private String name;
    private Integer ball;

    @OneToMany
    private Group group;


    //getters and setter

}

我想要一个名为 sum 的属性,spring 数据可以序列化但不持久化。换句话说,我不想在我的数据库中看到 'sum' 列。

我已经试过了@transient但是它是空的。

我该怎么做?

将 class 更改为 interface,然后像这样声明您的方法

    public interface GroupInterface { 
privte String groupName; 
private Long sum
}

.....

@Query(SELECT sum(a) as sum, groupNameColumn as groupName from ... inner join group ... group by ...
public List<GroupInterface> getMyResults(add some arguments if needed)

注意查询必须 return 2 列

感谢@Antoniosss!编辑他的回答:

What you want is to make a projection, and this is how you make projections in spring data. You can go up that hill and use proper constructor for that:

@Query(SELECT new full.qualified.name.of.class(sum as sum, ..... other arguments) from ... )

这就是我所做的并按预期工作。

所以,我添加了一个带有 @transient 注释的属性:

public class Group{
    @Id @Genera...
    private Integer id;
    private String group;

    @Transient
    private Integer sum;

    //getters and setter

}