Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing CRUDRepository's findBy() method on a field annotated by JoinColumn

Tags:

I'm kind of new to Spring JPA, so I apologize in advance if my question sounds basic. I have 2 entity objects: OrderInfo, and PersonInfo. The classes are as below:

@Entity @Table(name="order_info") @NamedQuery(name="OrderInfo.findAll", query="SELECT o FROM OrderInfo o") public class OrderInfo implements Serializable {      @Column(name="order_number")     private String orderNumber;      //bi-directional many-to-one association to PersonInfo     @ManyToOne     @JoinColumn(name="person_id")     private PersonInfo personInfo;      public String getOrderNumber() {         return this.orderNumber;     }      public void setOrderNumber(String orderNumber) {         this.orderNumber = orderNumber;     }      public PersonInfo getPersonInfo() {         return this.personInfo;     }      public void setPersonInfo(PersonInfo personInfo) {         this.personInfo = personInfo;     }   } 

And the Person entity:

@Entity @Table(name="person_info") @NamedQuery(name="PersonInfo.findAll", query="SELECT p FROM PersonInfo p") public class PersonInfo implements Serializable {      //bi-directional many-to-one association to OrderInfo     @OneToMany(mappedBy="personInfo")     private List<OrderInfo> orderInfos;      public List<OrderInfo> getOrderInfos() {         return this.orderInfos;     }      public void setOrderInfos(List<OrderInfo> orderInfos) {         this.orderInfos = orderInfos;     }      public OrderInfo addOrderInfo(OrderInfo orderInfo) {         getOrderInfos().add(orderInfo);         orderInfo.setPersonInfo(this);          return orderInfo;     }      public OrderInfo removeOrderInfo(OrderInfo orderInfo) {         getOrderInfos().remove(orderInfo);         orderInfo.setPersonInfo(null);          return orderInfo;     }  } 

These two classes were auto-generated in Eclipse using JPA's create entityfromtable option.

Now, I'm trying to write a CRUDRepository to get OrderInfo given an orderNumber, and personId. If I had a personId field in the OrderInfo object, I could have written something like

@Repository public interface OrderRepository extends CrudRepository<OrderInfo, Integer>{     public OrderInfo findByPersonIdAndOrderNumber(@Param("personId") Long personId, @Param("orderNumber") String orderNumber);  } 

However, now the OrderInfo entity does not have a personId. Instead, it has a reference to a Person (Again, I did not write the entity classes. They were auto-generated by Eclipse). How should I write the findBy() method now?

Thanks in advance.

like image 708
drunkenfist Avatar asked Feb 28 '15 21:02

drunkenfist


People also ask

What is the return Data type of find all method in crud repository?

The Iterable<T> findAll() method returns all entities that are saved to the database. The T findOne(Long id) method returns the entity whose id is given as method parameter. If no entity is found, this method returns null.

What is @query annotation used for?

The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.

What is the difference between findBy and findAll in JPA?

Actually, the difference between findallBy and findby, is that : findAllBy returns a Collection but findBy returns Optional. so it's preferable to write List findAllBy instead of writing List findBy (but it will work also :p). and to write Optional findBy instead of Optional findAllBy.

What is difference between CrudRepository and JpaRepository?

CrudRepository mainly provides CRUD operations. PagingAndSortingRepository provide methods to perform pagination and sorting of records. JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.


1 Answers

I've found another solution, let's assume we have a User entities and Message entities.

@Entity public 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  }    @Entity public 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); } 
like image 136
Simon Ludwig Avatar answered Oct 22 '22 07:10

Simon Ludwig