我有一个与其他类具有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表中。任何人都可以解释我在哪里做错了!
找到整个代码