DAO层设计实现
这里我们使用Spring DATA JPA
来实现数据库操作,当然大家也可以使用Mybatis
,都是一样的,我们依然以用户表操作为例:
/**
* AdUserRepository for 用户数据库操作接口
* 继承自JpaRepository<AdUser, Long>,第一个参数AdUser代表当前要操作的实体类的class定义,第二个参数Long表示该类的主键类型
*
* @author <a href="mailto:[email protected]">Isaac.Zhang</a>
*/
public interface AdUserRepository extends JpaRepository<AdUser, Long> {
/**
* 根据用户名称获取用户
*
* @param username 名称
* @return 用户对象
*/
AdUser findByUserName(String username);
List<AdUser> findAllByUserName(String userName);
}
- JPARepository 的默认实现方法,如果我们只是继承了
JpaRepository
而没有实现具体的操作方法,我们也是可以通过使用它的默认方法来做CRUD
操作的,如下:
功能Service实现
创建service package,依然以用户操作为例,创建com.sxzhongf.ad.service.IUserService
和com.sxzhongf.ad.service.impl.UserServiceImpl
,UserServiceImpl
实现了IUserService
。
- 创建
IUserService
接口
/**
* IUserService for 用户service
*
* @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
*/
public interface IUserService {
/**
* 创建用户接口
*
* @param userRequestVO {@link UserRequestVO}
* @return {@link UserResponseVO}
* @throws AdException 错误
*/
UserResponseVO createUser(UserRequestVO userRequestVO) throws AdException;
List<AdUser> findAllByUserName(String userName);
}
- 使用
IUserService
接口
/**
* UserServiceImpl for 用户service
*
* @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
*/
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
private final AdUserRepository userRepository;
@Autowired
public UserServiceImpl(AdUserRepository userRepository) {
this.userRepository