package nju.seec.helper.dao; import nju.seec.helper.entity.Course; import nju.seec.helper.util.enums.ExceptionType; import nju.seec.helper.util.exception.HelperException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.Set; /** * @author cst */ @Repository public interface CourseDAO extends JpaRepository { /** * 封装findById * * @param id * @return */ default Course findCourseById(Long id) { return this.findById(id) .filter(course -> course.getDeleteAt() == 0) .orElseThrow(() -> HelperException.of(ExceptionType.NOT_FOUND, "找不到课程")); } /** * 检查老师是否已创建同名课程 * * @param teacherId * @param name * @param courseId * @return */ @Query("select case when count(c.id)>0 then true else false end " + "from Course c " + "where c.id<>?1 " + "and c.teacherId=?2 " + "and c.name=?3 " + "and c.deleteAt=0 ") boolean existsByTeacherIdAndName(Long courseId, Long teacherId, String name); /** * 查询老师创建的课程 * * @param teacherId * @param key * @param pageable * @return */ @Query("select c from Course c " + "where c.teacherId=?1 " + "and c.name like concat('%',?2,'%') " + "and c.deleteAt=0 ") Page findByTeacherIdAndKey(Long teacherId, String key, Pageable pageable); /** * 查询课程 * * @param key * @param pageable * @return */ @Query("select c from Course c " + "where (c.name like concat('%',?1,'%') or c.teacherName like concat('%',?1,'%')) " + "and c.deleteAt=0 ") Page findByKey(String key, Pageable pageable); /** * 按ID列表查询 * * @param courseIds * @param key * @param pageable * @return */ @Query("select c from Course c " + "where c.id in ?1 " + "and (c.name like concat('%',?2,'%') or c.teacherName like concat('%',?2,'%')) " + "and c.deleteAt=0 ") Page findByIdsAndKey(Set courseIds, String key, Pageable pageable); /** * 更新所有人信息 * * @param userId * @param userName */ @Transactional(rollbackFor = Exception.class) @Modifying @Query("update Course c " + "set c.teacherName=?2 " + "where c.teacherId=?1 ") void updateUser(Long userId, String userName); }