A j
A j

Reputation: 1087

How to write a Spring JPA query for a one to one relationship?

I am new to Spring JPA (or rather looking into it after a long time) and I need some help with writing JPA repository. I have an entity class Itinerary and User. There is a one to one relationship between the two.

@Entity
@Table(name = "ITINERARY")
public class Itinerary implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "Itinerary_IDGenerator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "Itinerary_IDGenerator", sequenceName = "Itinerary_IDGenerator", allocationSize = 1)
    private long id;

    @Basic(optional = false)
    @Column(nullable = false)
    @Temporal(TemporalType.DATE)
    private Date itineraryDate;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    User user;
}

@Entity
@Table(name = "USER")
public class User implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "User_IDGenerator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "User_IDGenerator", sequenceName = "User_IDGenerator", allocationSize = 1)
    private long id;

    @Basic(optional = false)
    @Column(unique = true, nullable = false)
    private String signInName;
}

I want to write a Spring JPA repository for the Itinerary entity to have a method that will return an itinerary for a user (with the specifid singInName) and the itinerary date. I have write the following interface, but I don't know how to specify the spring query. I have provided a JPA query that works.

public interface ItineraryRepository extends Repository<Itinerary, Long> {

    //String queryStr = "select i from Itinerary i where i.user.signInName = '" + signedInUser + "' and i.itineraryDate = :today";

    @Query(select i from Itinerary i where i.user.signInName = :signInName and i.itineraryDate = :today)
    Itinerary findBySignInNameAndDate(@Param("signInName") String signInName, @Param("itineraryDate") Date itineraryDate);

}

I get an error on the query.

Invalid derived query! No property signInName found for type Itinerary!

and

Syntax error on tokens, delete these tokens

How do I convert this query to a spring query? I could not find an example in the documentation. I am not sure if this is possible at all and whether I am using the repository incorrectly.

Upvotes: 4

Views: 7250

Answers (1)

pvpkiran
pvpkiran

Reputation: 27048

Use this method in your repository Interface. And no need of @Query

 findByItineraryDateAndUser_SignInName(Date itineraryDate, String signInName);

Spring data is intelligent enough to understand what query it needs to use to fetch results based on your method name(atleast in simple query cases).

User_SignInName specifies to look for a property signInName inside property user.

Upvotes: 10

Related Questions