spring - JPA - 在组 [javax.validation.groups.Default, ] 的持续时间内对类 [com.homelancer.models.User] 的验证失败
问题描述
我一直试图找出这个明显简单的问题,但我没有成功。本质上,我的实体“工作”与实体“用户”具有一对一的关系。
在尝试发布新工作时,我不想发送有关用户的所有信息,而只想发送封装在工作内的用户对象中的用户 ID。这是我的代码:
工作:
@Entity
@Table(name="TB_Job")
public class Job implements Serializable {
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Id long jobId;
private String title, description, location;
private boolean job_assigned, time_to_assigned, job_active;
Date createDate;
Time licitationTime;
private int stateId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(insertable = false, updatable = false)
private User ownerUserID;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn()
private User assignedUserID;
private int categoryID;
}
用户:
@Entity
@Table(name = "TB_User")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private long userId;
@Column(name = "email", nullable = false, unique = true)
@Email(message = "*Please provide a valid Email")
@NotEmpty(message = "*Please provide an email")
private String email;
@Column(name = "password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
private String password;
@NotEmpty(message = "*Please provide your name")
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
@NotEmpty(message = "*Please provide your last name")
private String lastName;
@Column(name = "active")
private int active;
@Column(name = "city")
@NotEmpty(message = "*Please provide your City name")
private String city;
// --------- FOREIGN KEYS ---------
// Column used to FK in AssocUserRole
@OneToOne(mappedBy = "user")
private AssocUserRole user;
// Column used to FK in Job
@OneToMany(mappedBy = "ownerUserID")
private Set<Job> ownerUserID;
// Column used to FK in Job
@OneToMany(mappedBy = "assignedUserID")
private Set<Job> assignedUserID;
// --------- FOREIGN KEYS ---------
}
控制器:
@RestController
@RequestMapping(path = "/api")
public class JobController {
@Autowired
private JobRepository jobRepository;
@Autowired
private JobService jobservice;
@PostMapping("/job/{ownerId}")
public Job createJob(@RequestBody Job job, @PathVariable(value = "ownerId") long ownerId) {
return jobservice.addJob(job, ownerId);
}
@PostMapping("/job")
public Job createJob(@RequestBody Job job) {
return jobservice.addJob(job);
}
}
服务:
@Service
public class JobService {
@Autowired
JobRepository jobRepository;
@Autowired
UserRepository userRepository;
public Job addJob(Job job, long ownerId) {
try {
// Checks if owner actually exists
User ownerUser = userRepository.findById(ownerId);
// If it does
if(ownerUser != null) {
// Checks if job does not exists already
if (jobRepository.findById(job.getJobId()) == null) {
// Gets and Sets Job Owner FK to Job
job.setOwnerUserID(ownerUser);
return jobRepository.save(job);
} else {
return null;
}
}
else{
return null;
}
} catch (Exception Ex) {
return null;
}
}
public Job addJob(Job job) {
try {
// Checks if job does not exists already
if (jobRepository.findById(job.getJobId()) == null) {
// Gets and Sets Job Owner FK to Job
//job.setOwnerUserID(ownerUser);
return jobRepository.save(job);
} else {
return null;
}
} catch (Exception Ex) {
return null;
}
}
}
如你们所见,我在 JobService 中有不同的方法。一个只接收作业,另一个接收作业和用户 ID。我的目标很简单:我发布了一份工作,并且我想正确地接受用户通讯员的外键。不幸的是,使用 2º 方法,我遇到了这个问题:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
Validation failed for classes [com.homelancer.models.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='*Please provide your password', propertyPath=password, rootBeanClass=class com.homelancer.models.User, messageTemplate='*Please provide your password'}
ConstraintViolationImpl{interpolatedMessage='*Please provide your last name', propertyPath=lastName, rootBeanClass=class com.homelancer.models.User, messageTemplate='*Please provide your last name'}
ConstraintViolationImpl{interpolatedMessage='*Please provide an email', propertyPath=email, rootBeanClass=class com.homelancer.models.User, messageTemplate='*Please provide an email'}
ConstraintViolationImpl{interpolatedMessage='*Please provide your name', propertyPath=firstName, rootBeanClass=class com.homelancer.models.User, messageTemplate='*Please provide your name'}
ConstraintViolationImpl{interpolatedMessage='*Please provide your City name', propertyPath=city, rootBeanClass=class com.homelancer.models.User, messageTemplate='*Please provide your City name'}
]
这只是发生,因为 JCA 试图在数据库中插入作业和用户。我只想插入作业,以及引用用户的 ID。
这是我的 POST 请求:
{
"category": "batatas",
"categoryID": 0,
"createDate": "2019-12-29T21:50:42.847Z",
"description": "teste bc",
"job_active": true,
"job_assigned": true,
"location": "povoa city",
"stateID": 1,
"time_to_assigned": true,
"title": "granda job",
"ownerUserID": {
"userId": 116
}
}
如果有人对我的实施问题的解决方案有任何想法,那将非常有帮助,因为我为此浪费了好几个小时,还没有找到好的解决方案。
谢谢
解决方案
是addJob
事务性的吗?
如果不是,那么ownerUser
当你调用jobRepository.save(job)
. 这意味着 JPA 将尝试添加它,就好像它是一个新用户一样。添加@Transactional
应该可以解决问题。
顺便说一句,如果您不打算User
与它一起更新,Job
您可能不想cascade = ALL
Job.ownerUserID
推荐阅读
- apache-kafka - 制作 Apache Storm 拓扑以使用来自 kafka 的最新偏移量
- android - 无法修复 Fabric 上的崩溃...在 recyclerview 方法中
- r - dplyr 之间的情况
- perl - Perl Mojolicious 模型
- c# - Amazon DynamoDB InvalidOperationException on AWS
- c++ - C++ template with variadic argument specialization for number of arguments
- python - 确定请求的速率限制
- android - CoordinatorLayout 中 RecyclerView 的滚动问题
- sql - 使用 SQL 在 Oracle 中获取重复的元组
- c# - 在异步任务期间关闭表单时转换方法中的异常