Writing CRUDRepository's findBy() method on a field annotated by JoinColumn
I've found another solution, let's assume we have a User entities and Message entities.
@Entitypublic class Message { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime date; @ManyToOne @JoinColumn(name = "id_user_sender") private User userSender; @NotNull private Long idUserReceiver; @NotNull @Length(min = 10) private String message; @NotNull private String idConversation; @NotNull Boolean userHasRead; //Getters and Setters}@Entitypublic class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //Some other properies like email,name etc //Getters and setters}
Now i need to find all messages by id_user_sender.
public interface MessageRepository extends JpaRepository<Message,Long>,TransactionRepositoryCustom { List<Message> findByUserSenderId(Long idUser);}
Explantion:In the Message entity i have a User Object named 'userSender'. The userSender has a field named 'id'.
So 'findByUserSenderId' search for the id in the userSender Object.
Another possibilty is to pass a full User object to the message repository as in the example below: (The User object must contain only the id)
public interface MessageRepository extends JpaRepository<Message,Long>,TransactionRepositoryCustom { List<Message> findByUserSender(User user);}
Use a JPQL query:
@Query("select o from OrderInfo o where o.orderNumber = :orderNumber" + " and o.personInfo.id = :personId")
I think you need to update the spring data jpa version.I am currently using spring-data-jpa-2.0.2.RELEASE and it works well.
Also, it works for both the cases.You can define your interface method as -
List<Message> findByUserSender(User user);
or -
List<Message> findByUserSenderId(Long idUser);
Both these methods will create a left outer join on user_sender table to fetch the desired Message(s);