目录
1、Maven依赖及application.properties配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
如果想在控制台中打出sql语句,可以在application.properties中加入如下语句
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
关于ddl-auto属性的说明:
ddl-auto:create——每次运行该程序,没有表格会新建表格,表内有数据会清空
ddl-auto:create-drop——每次程序结束的时候会清空表
ddl-auto:update——每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
ddl-auto:validate——运行程序会校验数据与数据库的字段类型是否相同,不同会报错
2、实体类(BO)使用@Entity注释
注意在使用Spring Data JPA时并不需要先把表建起来,只要程序一跑,它会自动按DO类生成表格。
示例:
package com.xxx.modules.repository.entity;
import javax.persistence.*;
@Entity
@Table(name = "health_code_user",uniqueConstraints = {@UniqueConstraint(columnNames = "username")})
//这里的columnNames指的是表字段名,而不是类属性名
public class UserDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//主键生成策略:自增
@Column(name = "user_id")
private Long userId = 0L;
@Column(name = "username")
private String username;
@Column(name = "user_phone")
private String userPhone;
@Column(name = "user_password")
private String userPassword;
//每日上报是否填报
@Column(name = "report_status")
private Boolean reportStatus = false;
public Boolean getReportStatus() {
return reportStatus;
}
public void setReportStatus(Boolean reportStatus) {
this.reportStatus = reportStatus;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
3、Repository(dao层)使用@Repository,继承JpaRepository<>
继承JpaRepository<,>,第一个参数为实体类,第二个参数为主键。
会自动识别出find…By, read…By和get…By这样的前缀,从后面的命名中解析出查询的条件。方法命名的的第一个By表示查询条件的开始,多个条件可以通过And和Or来连接。如下代码所示,这里的UserRepository并不需要实现,就可以直接使用了。
除此之外JpaRepository(其实是CRUDRepository,JpaRepository是它的子接口)还提供了save、delete、findAll等方法,这些都可以直接用,根本就不用自己写。
package com.xxx.modules.repository;
import com.xxx.modules.repository.entity.UserDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<UserDO,Long> {
/**
* 根据用户名查询
* @param username
* @return
*/
UserDO findByUsername(String username);
}
4、在UserServiceImpl中进行调用
就可以直接用啦!在这里我就简单地在这层把它的返回值变成BO啦…BO在这里就是和DO相同的字段,去掉那些注释。在这里就省略BO类的代码和UserService接口的代码。
package com.xxx.modules.service.impl;
import com.xxx.modules.repository.UserRepository;
import com.xxx.modules.repository.entity.UserDO;
import com.xxx.modules.service.UserService;
import com.xxx.modules.service.bo.UserBO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public UserBO getUserByName(String username) {
UserDO userDO = userRepository.findByUsername(username);
if(userDO != null){
UserBO userBO = new UserBO();
BeanUtils.copyProperties(userDO,userBO);
return userBO;
}
return null;
}
@Override
public Boolean saveUser(UserBO userBO) {
UserDO userDO = new UserDO();
if(userBO != null){
BeanUtils.copyProperties(userBO,userDO);
//save()方法直到显式调用flush() 或commit()方法,才会将save操作相关联的数据刷新到DB。
//saveAndFlush()方法在执行期间立即刷新数据。
userRepository.saveAndFlush(userDO);
return true;
}
return false;
}
@Override
public List<UserBO> findAllUser() {
List<UserDO> allUserDOList = userRepository.findAll();
List<UserBO> allUsers = new ArrayList<UserBO>();
UserBO userBO = new UserBO();
for(UserDO userDO : allUserDOList){
BeanUtils.copyProperties(userDO,userBO);
allUsers.add(userBO);
}
return allUsers;
}
}
5、UserReqDTO、UserRespDTO和UserRegisterDTO
UserReqDTO、UserRespDTO分别封装登录接口的输入和输出参数
UserRegisterDTO封装了注册接口的输入参数
其实就是UserBO去掉一些不太需要的参数
package com.xxx.api.v1.dto;
public class UserReqDTO {
//用户名
private String username;
//密码
private String userPassword;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
package com.xxx.api.v1.dto;
public class UserRespDTO {
//用户Id
private Long userId;
//用户信息是否上报
private Boolean reportStatus;
//用户名
private String username;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Boolean getReportStatus() {
return reportStatus;
}
public void setReportStatus(Boolean reportStatus) {
this.reportStatus = reportStatus;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
package com.hik.health.api.v1.dto;
public class UserRegisterDTO {
//用户名
private String username;
//密码
private String userPhone;
//联系方式
private String userPassword;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
6、UserRestService和UserRestServiceImpl
注意在这里我使用了XxxResult封装了返回数据,也可以直接返回。
package com.xxx.api.v1;
import com.xxx.api.v1.dto.UserRegisterDTO;
import com.xxx.api.v1.dto.UserReqDTO;
import com.xxx.api.v1.dto.UserRespDTO;
import com.xxx.library.common.XxxResult;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/user/v1")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface UserRestService {
@POST
@Path("/login")
XxxResult<UserRespDTO> login(UserReqDTO userReqDTO);
@POST
@Path("/register")
XxxResult register(UserRegisterDTO userRegisterDTO);
}
package com.xxx.modules.provider;
import com.xxx.api.v1.UserRestService;
import com.xxx.api.v1.dto.UserRegisterDTO;
import com.xxx.api.v1.dto.UserReqDTO;
import com.xxx.api.v1.dto.UserRespDTO;
import com.xxx.modules.service.UserService;
import com.xxx.modules.service.bo.UserBO;
import com.xxx.library.common.XxxResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserRestServiceImpl implements UserRestService {
@Autowired
UserService userService;
@Override
public XxxResult<UserRespDTO> login(UserReqDTO userReqDTO) {
UserRespDTO userRespDTO = new UserRespDTO();
if(userReqDTO != null && userReqDTO.getUsername() != null && userReqDTO.getUserPassword() != null){
String username = userReqDTO.getUsername();
String password = userReqDTO.getUserPassword();
UserBO userBO = userService.getUserByName(username);
if(userBO != null && password.equals(userBO.getUserPassword())){
BeanUtils.copyProperties(userBO,userRespDTO);
return XxxResult.success(userRespDTO);
}
}
return XxxResult.fail("","FAIL");
}
@Override
public XxxResult register(UserRegisterDTO userRegisterDTO) {
UserBO userBO = new UserBO();
BeanUtils.copyProperties(userRegisterDTO,userBO);
if(userService.saveUser(userBO)){
return XxxResult.success();
}
return XxxResult.fail("","出错啦~用户名可能重复");
}
}