Spring Boot Data JPA manyToMany添加项引发UnsupportedOperationException

时间:2018-09-08 19:23:02

标签: java spring spring-boot spring-data-jpa many-to-many

Company.java:

import org.apache.commons.net.time.TimeTCPClient;

public final class GetTime {

public static final void main(String[] args) {
    try {
        TimeTCPClient client = new TimeTCPClient();
        try {
            client.setDefaultTimeout(60000);
            client.connect("time.nist.gov");
            System.out.println(client.getDate());
        }
        catch (IOException e) {
           e.printStackTrace();
        }
        finally {
           client.disconnect();
        }
    }
}

用户

time.nist.gov

存储库:

@Entity
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
@Data
public class Company {
    @Id
    @GeneratedValue(generator="system-uuid")
    @GenericGenerator(name="system-uuid", strategy = "uuid")
    String id;

    String name;

    @ManyToMany
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<User> employees = new ArrayList<>();
    // Snip
}

因此,我从数据库中加载了一家公司并这样做:

@Entity
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
@Data
public class User {
    @Id @GeneratedValue(generator="system-uuid")
    @GenericGenerator(name="system-uuid", strategy = "uuid")
    String id;

    @NotNull
    String email;

    @NotNull
    Date created = new Date();

    @ManyToMany(mappedBy="employees")
    @LazyCollection(LazyCollectionOption.FALSE)
    List<Company> employedByCompanies = new ArrayList<>();
    // Snip
}

我得到了例外:

public interface CompanyRepository extends CrudRepository<Company, String> {
}

public interface UserRepository extends CrudRepository<User, String> {
}

JPA为什么不使用我可以更新的类?

这是我的gradle文件:

company.getEmployees().add(timesheetUser);

1 个答案:

答案 0 :(得分:0)

无论出于何种原因,我都不得不将List更改为Set,并且可以使用。

赞:

@Entity
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
@Data
public class User {
    @Id @GeneratedValue(generator="system-uuid")
    @GenericGenerator(name="system-uuid", strategy = "uuid")
    String id;

    @NotNull
    String email;

    @NotNull
    Date created = new Date();

    @ManyToMany(mappedBy="employees")
    @LazyCollection(LazyCollectionOption.FALSE)
    // List DOES NOT WORK HERE!
    Set<Company> employedByCompanies = new HashSet<>();
    // Snip
}

不知道为什么...