Spring Data JPA
The Repository pattern is commonly used in Java Spring applications. It abstracts the story and retrieval of data from a data store. The repository is typically called from a Service class. For a web application, the Service class is called from the Controller class.
First, we define the entity class with the fields that we have to store:
package com.pockettheories;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class CarEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int ID;
public String makeName;
public Integer modelYear;
public String modelName;
}
When building a console application, the Main class can be used to call the Service class, and to inject a Service object instance, we @Autowired it.
@Autowired
private CarService carService;
The Service class contains methods that in turn call the Repository class:
package com.pockettheories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CarService {
@Autowired
private CarRepository carRepository;
public void addCar(CarEntity car) {
carRepository.addCar(car);
}
public List getAllCars() {
return carRepository.getAllCars();
}
}
The Repository class interacts with the EntityManager, from JPA. The EntityManager can be used to execute JPQL queries.
package com.pockettheories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Transactional
@Repository
public class CarRepository implements ICarRepository{
@PersistenceContext
private EntityManager entityManager;
@Override
public void addCar(CarEntity car) {
entityManager.persist(car);
}
@Override
public CarEntity getCarById(int carId) {
return entityManager.find(CarEntity.class, carId);
}
@Override
public List getAllCars() {
return entityManager.createQuery("select c from CarEntity c").getResultList();
}
}