002. Basic (Single Entity with CRUD) - dkkahm/study-spring-jpa GitHub Wiki
Entity
@Entity
public class Course {
@Id
@GeneratedValue
private Long id;
private String name;
public Course() {
}
public Course(String name) {
this.name = name;
}
public Course(Long id, String name) {
this.id = id;
this.name = name;
}
.... // getters and setters
}
Repository
@Repository
@Transactional
public class CourseRepository {
@Autowired
EntityManager em;
public Course findById(Long id) {
return em.find(Course.class, id);
}
public Course save(Course course) {
if(course.getId() == null) {
em.persist(course);
} else {
em.merge(course);
}
return course;
}
public void deleteById(Long id) {
Course course = findById(id);
em.remove(course);
}
Simple JPQL
Query (Select)
Query query = em.createQuery("Select c From Course c")
List resultList = query.getResultList();
TypedQuery (Select)
TypedQuery<Query> query = em.createQuery("Select c From Course c", Course.class)
List<Course> resultList = query.getResultList();
with where
TypedQuery<Query> query = em.createQuery("Select c From Course c where name like '%100 Steps'", Course.class)
List<Course> resultList = query.getResultList();
@NamedQueries(
value= {
@NamedQuery(name="query_get_all_courses", query="Select c From Course c"),
@NamedQuery(name="query_get_100_step_courses", query="Select c From Course c where name like '%100 Steps'")
}
)