使用@Query使用Spring Data创建自定义查询

时间:2017-01-11 14:49:08

标签: java spring

我有一个Message实体和一个Admin实体。 消息是:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column(name = "text")
private String text;

@OneToOne
@JoinColumn(name = "id_from")
private Admin idFrom;

@OneToOne
@JoinColumn(name = "id_too")
private Admin idToo;

管理员是:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column(name = "username")
private String username;

@Column(name = "password")
private String password;

@Column(name = "email")
private String email;

如何创建此查询:

select id_from, text from message
where id_from = from and id_too = too
or id_from = too and id_too = from; 

使用@Query注释?

这样的事情:

@Query("SELECT m FROM Message m WHERE m.id_from = :from.id and m.id_too = :too.id or m.id_from = :too.id and m.id_too = :from.id")
List<Message> findMessages(@Param("from") Admin from, @Param("too") Admin too);

谢谢

1 个答案:

答案 0 :(得分:0)

@Query("SELECT m FROM Message m WHERE m.idFrom.id = :fromId and m.idToo.id = :tooId or m.idFrom.id = :tooId and m.idToo.id = :fromId")
List<Message> findMessages(@Param("fromId") Long fromId, @Param("tooId") Long tooId);