Q:

How to make uniqe filed in entity, but relatively manyToOne entity?

public class Task {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private UUID id;

@Column(nullable = false)
private String title;

@JoinColumn(name = "user_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private User user;

}

public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private UUID id;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Task> tasks = new ArrayList<>();

}

I want to make the title unique, but not in the queue in the table, I need a unique title for the user. The user should not have a task equal to the title with other tasks of this user.

A:

The combination that you are looking for is then that a task should be unique based on a combination of taskTitle + user: you have to add this to the Task table: you can do that with annotation
 @Table(
    name="UNQ_CONSTRAINT_NAME", 
    uniqueConstraints=
        @UniqueConstraint(columnNames={"title", "user_id"})
 )
 public class Task{
     //...
 }

In this way you will never get a double row in your Task table with the same  title + user

