Pergunta

Existe alguma API/interface fluente JPA 1.0 para edifício de consulta? Estou usando o OpenJpa 1.x, então estou preso ao JPA1.

eu encontrei QuerybyProxy, mas seu repo Maven não está funcionando corretamente.

Foi útil?

Solução

Se você está preso ao JPA 1.0, considere usar Querydsl Isso fornece uma API fluente do TypeAfe na parte superior do JPA. Você precisará usar uma versão antes de 1.6.0, ou seja, 1.5.4 (eles mudaram para o JPA 2.0 em 1.6.0). Esta é a sua melhor opção.

Outras dicas

Resposta curta é não. No entanto, depende do provedor que você está usando. Por exemplo, se você estiver usando o Hibernate, sempre poderá obter a API de critérios da Hibernate. No entanto, no JPA 1.0, isso não é suportado. No JPA 2.0, porém é.

Você pode usar o padrão de interface fluente com JPA e Hibernate. eu escrevi um artigo que explica este tópico em grande detalhe.

Para resumir, se você estiver usando o Hibernate, basta modificar os setters para devolver a entidade:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    public Post() {}

    public Post(String title) {
        this.title = title;
    }

    @OneToMany(
        cascade = CascadeType.ALL, 
        orphanRemoval = true, 
        mappedBy = "post"
    )
    private List<PostComment> comments = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public Post setId(Long id) {
        this.id = id;
        return this;
    }

    public String getTitle() {
        return title;
    }

    public Post setTitle(String title) {
        this.title = title;
        return this;
    }

    public List<PostComment> getComments() {
        return comments;
    }

    public Post addComment(PostComment comment) {
        comment.setPost(this);
        comments.add(comment);
        return this;
    }
}

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

    private Date createdOn;

    @ManyToOne
    private Post post;

    public Long getId() {
        return id;
    }

    public PostComment setId(Long id) {
        this.id = id;
        return this;
    }

    public String getReview() {
        return review;
    }

    public PostComment setReview(String review) {
        this.review = review;
        return this;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public PostComment setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
        return this;
    }

    public Post getPost() {
        return post;
    }

    public PostComment setPost(Post post) {
        this.post = post;
        return this;
    }
}

Dessa forma, você pode construir os pais e as entidades infantis como esta:

doInJPA(entityManager -> {
    Post post = new Post()
    .setId(1L)
    .setTitle("High-Performance Java Persistence")
    .addComment(
        new PostComment()
        .setReview("Awesome book")
        .setCreatedOn(Timestamp.from(
            LocalDateTime.now().minusDays(1).toInstant(ZoneOffset.UTC))
        )
    )
    .addComment(
        new PostComment()
        .setReview("High-Performance Rocks!")
        .setCreatedOn(Timestamp.from(
            LocalDateTime.now().minusDays(2).toInstant(ZoneOffset.UTC))
        )
    )
    .addComment(
        new PostComment()
        .setReview("Database essentials to the rescue!")
        .setCreatedOn(Timestamp.from(
            LocalDateTime.now().minusDays(3).toInstant(ZoneOffset.UTC))
        )
    );
    entityManager.persist(post);
});

Se você se preocupa com a portabilidade da JPA, talvez não queira violar a especificação Java Bean; nesse caso, você precisa adicionar os métodos de interface fluente ao longo dos setters regulares:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    public Post() {}

    public Post(String title) {
        this.title = title;
    }

    @OneToMany(
        cascade = CascadeType.ALL, 
        orphanRemoval = true, 
        mappedBy = "post"
    )
    private List<PostComment> comments = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Post id(Long id) {
        this.id = id;
        return this;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Post title(String title) {
        this.title = title;
        return this;
    }

    public List<PostComment> getComments() {
        return comments;
    }

    public Post addComment(PostComment comment) {
        comments.add(comment.post(this));
        return this;
    }
}

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

    private Date createdOn;

    @ManyToOne
    private Post post;

    public Long getId() {
        return id;
    }

    public PostComment setId(Long id) {
        this.id = id;
        return this;
    }

    public String getReview() {
        return review;
    }

    public void setReview(String review) {
        this.review = review;
    }

    public PostComment review(String review) {
        this.review = review;
        return this;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public PostComment createdOn(Date createdOn) {
        this.createdOn = createdOn;
        return this;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public PostComment post(Post post) {
        this.post = post;
        return this;
    }
}

O edifício da entidade é quase idêntico ao anterior:

doInJPA(entityManager -> {
    Post post = new Post()
    .id(1L)
    .title("High-Performance Java Persistence")
    .addComment(new PostComment()
        .review("Awesome book")
        .createdOn(Timestamp.from(
            LocalDateTime.now().minusDays(1).toInstant(ZoneOffset.UTC))
        )
    )
    .addComment(new PostComment()
        .review("High-Performance Rocks!")
        .createdOn(Timestamp.from(
            LocalDateTime.now().minusDays(2).toInstant(ZoneOffset.UTC))
        )
    )
    .addComment(new PostComment()
        .review("Database essentials to the rescue!")
        .createdOn(Timestamp.from(
            LocalDateTime.now().minusDays(3).toInstant(ZoneOffset.UTC))
        )
    );
    entityManager.persist(post);
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top