您好,登錄后才能下訂單哦!
Hibernate 提供了內置的驗證框架,可以對實體類的屬性值進行校驗。以下是使用 Hibernate 進行數據校驗的步驟:
@NotEmpty
、@NotNull
、@Size
、@Pattern
等,以定義屬性值的校驗規則。import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "用戶名不能為空")
@Size(min = 3, max = 20, message = "用戶名長度必須在3到20個字符之間")
private String username;
@NotEmpty(message = "密碼不能為空")
@Size(min = 6, max = 20, message = "密碼長度必須在6到20個字符之間")
private String password;
// getter 和 setter 方法
}
pom.xml
文件中添加以下依賴:<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
Validator
對象對實體類的屬性值進行校驗。如果校驗失敗,可以拋出自定義的異常或返回錯誤信息。import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
public class UserService {
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public void createUser(User user) {
Set<ConstraintViolation<User>> violations = validator.validate(user);
if (!violations.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation<User> violation : violations) {
sb.append(violation.getMessage()).append("; ");
}
throw new IllegalArgumentException("參數校驗失敗: " + sb.toString());
}
// 保存用戶或執行其他操作
}
}
IllegalArgumentException
異常,返回相應的錯誤信息給客戶端。import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
通過以上步驟,可以使用 Hibernate 對實體類的屬性值進行校驗,并在校驗失敗時返回相應的錯誤信息。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。