0

我一直试图找出这个明显简单的问题,但我没有成功。本质上,我的实体“工作”与实体“用户”具有一对一的关系。

在尝试发布新工作时,我不想发送有关用户的所有信息,而只想发送封装在工作内的用户对象中的用户 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  
  }
}

如果有人对我的实施问题的解决方案有任何想法,那将非常有帮助,因为我为此浪费了好几个小时,还没有找到好的解决方案。

谢谢

4

2 回答 2

0

addJob事务性的吗?

如果不是,那么ownerUser当你调用jobRepository.save(job). 这意味着 JPA 将尝试添加它,就好像它是一个新用户一样。添加@Transactional应该可以解决问题。

顺便说一句,如果您不打算User与它一起更新,Job您可能不想cascade = ALLJob.ownerUserID

于 2019-12-31T16:01:45.963 回答
0

这个 if 语句不好,因为您的请求正文中没有 id,所以它始终为空。

if (jobRepository.findById(job.getJobId()) == null) {

最好在 JobRepository 中创建一个新方法,例如:

Job findFirstByTitle(String title);

这是一个返回工作的标题。但主要问题是在 ownerUserID 字段中删除 insertable = false 。所以这个一定是:

@JoinColumn(updatable = false)
private User ownerUserID;

因为如果您保存作业对象,则应在此字段中插入引用。

于 2019-12-30T16:05:49.070 回答