简体   繁体   中英

How to use “findBy” in an Entity with a Composite PK (Hibernate JPA)

I am learning with bootspring.

findByDate(int date); used to work until I've moved int Date into the inner class.

Now I can save new entries but I can't retrive them byDate

What do I need to change?

@Transactional
public interface ExpirationDAO extends JpaRepository<ExpirationDTO, Long> {

    public ExpirationDTO findByDate(int date);
}

and

@Embeddable
    public static class IdKey implements Serializable{
        @NotNull
        int date;
        @ManyToOne
        ProductDTO product;

        public IdKey(){
        }
         //setters and getters
    }
    @EmbeddedId
    private IdKey id;
    @NotNull
    int units;

    public ExpirationDTO(){     
    }
       //setters and getters
}

throws this exception:

org.springframework.data.mapping.PropertyReferenceException: No property date found for type ExpirationDTO!

You should include name of embedded key class in repository instead of Long. Try this one (not tested):

public interface ExpirationDAO extends JpaRepository<ExpirationDTO, IdKey> {
    public List<ExpirationDTO> findByIdDate(int date);
}

There after findBy Id is yours EmbeddedId and Date is attribute of embeddable class. And one more thing: if you use only part of embedded key, you can't expect only one result...

You should include name of embedded key class in repository and also add an underscore (_)

Tested below:

public interface ExpirationDAO extends JpaRepository<ExpirationDTO, IdKey> {
    public List<ExpirationDTO> findByIdKey_Date(Date date);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM