无法在ManyToMany关系中复制实体

时间:2018-05-20 10:38:42

标签: hibernate jpa manytomanyfield

我有一个与其他类具有ManyToMany关系的实体类。我想通过更改其name属性在该实例的表中创建一个新条目。

Employee.java`

@Entity
@Table(name = "employee")
public class Employee {
    public Employee() {
        super();
    }

    public Employee(String name, List<Address> address) {
        super();
        this.name = name;
        this.setAddress(address);
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE,CascadeType.DETACH },fetch=FetchType.EAGER)
    @JoinTable(name = "employee_address", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = {
            @JoinColumn(name = "address_id") })
    private List<Address> address;

    @OneToOne
    private Department department;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public List<Address> getAddress() {
        return address;
    }

    public void setAddress(List<Address> address) {
        this.address = address;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}

Address.java

@Entity
@Table(name = "Address")
public class Address {
    public Address() {
        super();
    }

    public Address(String address) {
        super();
        this.address = address;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String address;

    @ManyToMany(mappedBy = "address", cascade = CascadeType.REMOVE)
    private List<Employee> employee;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

DataRetrivalServiceImpl.java

@Service
public class DataServiceImpl {
    @Autowired
    private EntityManager entityManager;
@Transactional
    public void copyEmpoyee() {
        Employee e = employeeRepo.findOneById(15);
        entityManager.detach(e);
        e.setId(0);
        e.setName("new Name");
        //employeeRepo.save(e);
        entityManager.persist(e);
    }

当我运行代码时,在employee表中创建一个新条目,但不在Address表中。任何人都可以解释我在哪里做错了!

可以在 - https://github.com/iftekharkhan09/JPAHibernateProject

找到整个代码

0 个答案:

没有答案