Search code examples
hibernatejpatransient

Transient Getter is persisted JPA Hibernate


although I marked some getter methods in my class as @Transient (javax.persistence) the results when calling the method are persisted in the database:

@Entity
@Table(name = "Song")
@EntityListeners(AuditingEntityListener.class)
public class Song implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "artist_id")
    private Artist artist;

      @Transient
    public static final Path MUSIC_DIRECTORY = Paths.get(System.getProperty("user.home"), "TUBEMIRROR-MUSIC");

    @Transient
    public String getPathBySongId(){
        return Paths.get(MUSIC_DIRECTORY.toString(), this.getYoutubeId() + ".mp3").toString();
    }
}

Since there is a 1:1 relationship of songId to the path of the song on the filesystem I rather do not want to persist it. When I read the list of all songs in the database using a JPARepository I see that the field was persisted despite the notation.

Can someone tell me why this happens?


Solution

  • If using (JPA) annotations, you are supposed to annotate EITHER fields OR getters, but NOT BOTH. Your annotation of fields is being used and consequently the annotation of the transient getter (getPathBySongId) if being ignored. Annotate getters ONLY if you want that to be respected.

    JPA annotations on a static final are pointless, since such fields are not persisted anyway