Ayush
Ayush

Reputation: 179

Spring JPA using primary key within @Embeddable class

In my application i have a scenario to fetch data from entity based on give input code and date. The combination of code and date will be unique and will return a single record.

Below is my entity

class JpaEntity
{
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private id ;
        private String code;
        private Date date;
        private title;

        //Getters and Setters

}

I have tried below approcah by changing the entity.

class JpaEntity
{
        private String title;
        
        //Getters and setters
        
        @EmbededId
        private EntityId entityID
        
        @Embedable
        public static class EntityId implements Serializable{
        
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private id ;
            private String code;
            private Date date;
            
            //Getters and Setters
        
        }
}

I am using the entity to search based on code and date

public interface PersistentDAO extends JpaRepository<JpaEntity,String> {
{
    @Query("SELECT cal FROM JpaCalendar cal" + " WHERE cal.calendarId.currencyCode=:currencyCode "
            + " AND cal.calendarId.date=:date")
    Optional<JpaCalendar> findById(String currencyCode, Date date);
    JpaEntity findByID(String code,Date date)

}

But the JPA is throwing error saying Component Id is not found. is it mandatory all the field in @Embedable are primary? is it possible @Embedable class (composite id) contain the both primary and non-primay keys.

Since i am not supposed to change the structure of the table is there any way to achieve following: Fetch record based on give code and date. Insert new record where in id the primary key should be auto incremented

Please suggest.

Upvotes: 0

Views: 1631

Answers (1)

Eklavya
Eklavya

Reputation: 18440

Use @Embedded & @Embeddable and don't use static class inside class

class JpaEntity
{
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private id ;
        @Embedded
        private CodeDate codeDate;
        private title;
}
@Embeddable
class CodeDate {
        private String code;
        private Date date;
}

You can use Jpa method naming query and create a CodeDate object call like this

public interface PersistentDAO extends JpaRepository<JpaEntity,String> {
{
    JpaEntity findByCodeDate(CodeDate codeDate);
}

Upvotes: 1

Related Questions