我有两个类,它们的表彼此具有双向关系。 员工可以与多个服务类别相关联,反之亦然。连接表在Service Categories类中声明。
当我希望保存Employee对象时,在连接表中没有保存任何内容,但如果我尝试打印与员工相关的服务类别,那么我将获得所有详细信息
if(employee.getServiceCategories()!= null && employee.getServiceCategories().size()>0){
for(ServiceCategory serviceCategory : employee.getServiceCategories()){
logger.debug("employee's serviceCategory id : " + serviceCategory.getId());
logger.debug("employee's ServiceCat Name : " + serviceCategory.getServiceCatName());
}
}
Employee.java
@Entity
@Table(name = "employee")
public class Employee extends BaseEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy="employees")
private List<ServiceCategory> serviceCategories = new ArrayList<>();
}
ServiceCategory.java
@Entity
@Table(name = "servicecategory")
public class ServiceCategory extends BaseEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(targetEntity = Employee.class, cascade = { CascadeType.ALL })
@JoinTable(name = "servicecategory_employee", joinColumns = { @JoinColumn(name = "servicecatid") }, inverseJoinColumns = { @JoinColumn(name = "empid") })
private List<Employee> employees = new ArrayList<>();
}
感谢您的帮助。
更新
我将Employee.java中的代码更改为
@ManyToMany(mappedBy="employees", cascade = CascadeType.ALL)
private List<ServiceCategory> serviceCategories = new ArrayList<>();
此外,我现在使用以下代码,同时在我的DAO类中保存Employee
public void addEmployee(Employee employee) throws SmrException {
Session session = this.sessionFactory.getCurrentSession();
session.merge(employee);
logger.info("Employee saved successfully, employee Details="
+ employee);
}
但结果仍然相同。我无法在连接表中保存数据
答案 0 :(得分:0)
您正在设置关联的反面(具有 #circular {
width: 150px;
height: 150px;
border-radius: 150px;
-webkit-border-radius: 150px;
-moz-border-radius: 150px;
background: url(http://media-cdn.tripadvisor.com/media/photo-s/02/5f/16/e4/la-jolla-cove.jpg) no-repeat;
position: absolute;
top: 15px;
left: 35px;
}
div.SanDiego {
background-color: #ff604c;
padding: 15px;
opacity: 0.5;
position: absolute;
top: 220px;
left: 35px;
font-size: 20px;
color: #999;
}
#maps {
background-color: white;
height: 300px;
width: 220px;
border-style: solid;
border-color: #B4B4B4;
float: left;
position: relative;
}
#menu {
right: 52px;
bottom: 638px;
}
body {
background-color: #E8E8E8;
}
nav {
background-color: white;
height: 75px;
width: 1140px;
float: left;
border-style: solid;
border-color: #B4B4B4;
margin-left: 30px;
}
nav ul {} nav ul li {
list-style-type: none;
width: 150px;
float: left;
text-align: center;
}
li a {
text-decoration: none;
color: #999;
line-height: 50px;
display: block;
}
li a:hover {
text-decoration: underline;
color: #FF604C;
}
属性的那个)。 JPA仅考虑所有者方(没有 mappedBy
属性)。
您需要将员工添加到其所有服务类别,而不仅仅是将服务类别添加到员工。