2. The JDBC API makes it possible to
do three things:
• Establish a connection with a
database or access any tabular
data source
• Send SQL statements
• Process the results
JDBC (1)
4. JPA(1)
Includes:
• the API itself, defined in the
javax.persistence package
• the Java Persistence Query
Language (JPQL)
• object/relational metadata
DAO -> Persistance
5. JPA(2)
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "date")
private Date date;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
}
6. JPA(3)
Product product = new Product();
Order order = new Order();
order.setProduct(product);
entityManager.persist(product);
entityManager.persist(order);
Product dbProduct = entityManager.find(Product.class, product.getId());
String name = "InitialName";
String query = "SELECT p FROM Product p WHERE p.name LIKE
:productName";
Product product = entityManager.createQuery(query, Product.class)
.setParameter("productName", name)
.getSingleResult();
8. Spring Data(2)
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
<S extends T> S save(S entity);
T findOne(ID primaryKey);
Iterable<T> findAll();
Long count();
void delete(T entity);
boolean exists(ID primaryKey);
// … more functionality omitted.
}
9. Spring Data(3)
public interface PersonRepository extends Repository<User, Long> { … }
List<Person> findByLastname(String lastname);
public class SomeClient {
@Autowired
private PersonRepository repository;
public void doSomething() {
List<Person> persons = repository.findByLastname("Matthews");
}
}
10. Spring Data(4)
interface UserRepositoryCustom {
public void someCustomMethod(User user);
}
class UserRepositoryImpl implements UserRepositoryCustom {
public void someCustomMethod(User user) {
// Your custom implementation
}
}
public interface UserRepository extends CrudRepository<User, Long>,
UserRepositoryCustom {
// Declare query methods here
}
11. Spring Data(5)
Spring Data JPA
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
@Query("select u from User u")
Stream<User> findAllByCustomQueryAndStream();
Spring Data REST
Expose DB through REST (JSON in HAL notation)