Social Media

Calling Database Views From Spring Data JPA

Im not going to go into pro’s and con’s as to whether database views are the correct approach with a JPA subsystem, but will say that a lot of the time there isnt a discussion as the view already exists and you will just need to use it to complete your task

Lets consider this view –

CREATE VIEW my_view AS
SELECT my_view_id, my_view_name FROM my_table;

We map this to a JPA object as –

@Entity
@Table(name = "my_view")
public class MyView implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "my_view_id")
private Long myViewId;
@NotNull
@Column(name = "my_view_name")
private String myViewName;
}

We then create a repository –

import org.springframework.data.repository.CrudRepository;
public interface MyViewRepository extends CrudRepository<MyView, Long> {
}

We can then call this –

@Autowired
private MyViewRepository myViewRepository;
// ...
long count = myViewRepository.count();

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment:

1 comment
Add Your Reply