Entity Manager:
⚫ It is from data-jpa.
Add Entity to Database
public void persist(Object entity);
@Override
@Transactional //Handles transaction management
public void save(Student theStudent) {
// if id=0 then save/insert else error
entityManager.persist(theStudent); //Save theJava object
}
public <T> T merge(T entity);
@Override
@Transactional //Handles transaction management
public void save(Student theStudent) {
// if id=0, then save/insert else update
entityManager.merge(theStudent); //Save theJava object
}
Find Entity by Id
public <T> T find(Class<T> entityClass, Object primaryKey);
@Override //No need to add @Transactional since we are doing a query
public Student findById(Integer id) {
return entityManager.find(Student.class, id); //If not found, returns null
}
Find All Entities
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
@Override
public List<Student> findAll() {
//
// create query
//
// Name of JPA Entity … the class name
// this is NOT the name of the database table
// All JPQL syntax is based on
// entity name and entity fields
TypedQuery<Student> theQuery = entityManager.createQuery("FROM Student", Student.class);
// return query results
return theQuery.getResultList();
}
Find Entities Based On Condition
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
@Override
public List<Student> findByLastName(String theLastName) {
// create query
TypedQuery<Student> theQuery = entityManager.createQuery(
"FROM Student WHERE lastName=:theData", Student.class);
// set query parameters
theQuery.setParameter("theData", theLastName);
// return query results
return theQuery.getResultList();
}
Update Entity
public <T> T merge(T entity);
@Override
@Transactional //Add @Transactional since we are performing an update
public void update(Student theStudent) {
entityManager.merge(theStudent);
}
Delete Entity
public void remove(Object entity);
@Override
@Transactional //Add @Transactional since we are performing a delete
public void delete(Integer id) {
// retrieve the student
Student theStudent = entityManager.find(Student.class, id);
// delete the student
entityManager.remove(theStudent);
}
Delete All Entities
public Query createQuery(String qlString);
@Override
@Transactional //Add @Transactional since we are performing a delete
public int deleteAll() {
int numRowsDeleted = entityManager.createQuery("DELETE FROM Student").executeUpdate();
return numRowsDeleted;
}