Geek
Geek

Reputation: 1344

Search the records without a primary key

I have a Spring Entity class as below.

@Entity
@Table(name = "Calendar_Month")
public class Calendar_Month {
    @Id
    @Transient
    private int Calendar_Month_ID;
    private String Calendar_Year;
    private String Calendar_Month;
    private String Calendar_Country;

with corresponding getters and setters.

I have written a Spring data jpa repository for this table access as below.

@Resource
public interface CalendarMonthRepository extends CrudRepository<Calendar_Month, Long> {

}

But i want to read all the records using Calendar_Month value. But Calendar_Month is not a primary key. So i was wondering how to achieve this.

Can someone help me with this please.

Upvotes: 0

Views: 6776

Answers (2)

ikettu
ikettu

Reputation: 1203

You should be able to use query methods like this

@Repository
public interface CalendarMonthRepository extends CrudRepository<Calendar_Month, Long> {
   List<Calendar_Month> findByCalendar_Month(String calendar_Month)
}

You can find what kind of queries can be created this way from Spring Data documentation.

Upvotes: 3

Przemek
Przemek

Reputation: 36

You have marked Calendar_Month_ID with @Id. Annotation @Id "Specifies the primary key of an entity.". Either make Calendar_Month_ID primary key, or move @Id annotation to real primary key of this entity. In your CalendarMonthRepository, you should be able to create method like:

public CalendarMonth findByCalendarMonthId(Long calendarMonthId)

Creation of CrudRepository methods: https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

P.S. Check java variableNamingConvention: Variable naming conventions in Java?

Upvotes: 1

Related Questions