我建立一個樣品之間的多對多關係:(1)用戶 - ()ACCESSLEVEL() - (1)角色Hibernate的春天:@ManyToMany DataIntegrityViolationException ConstraintViolationException
我已經實現3班在Java中使用Hibernate實現如下:
類用戶
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue
@Column(name="USER_ID")
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "access_level", joinColumns = {
@JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
private Set<Role> roles = new HashSet<Role>(0);
級角色
@Entity
@Table(name="role")
public class Role {
@Id
@GeneratedValue
@Column(name="role_id")
private Integer id;
@Column(name="role_name")
private String roleName;
類ACCESSLEVEL
@Entity
@Table(name="access_level")
public class AccessLevel {
@Id
@GeneratedValue
private Integer id;
@Column(name="role_id")
private Integer roleId;
@Column(name="user_id")
private Integer userId;
問題:
當我持續使用合併方法的用戶豆然後異常出現:
@Service
public class UserServiceImpl implements UserService {
@PersistenceContext
private EntityManager em;
@Override
@Transactional
public void save(User user) {
em.merge(user);
}
異常
org.springframework.web.util.NestedServletException:傳進程
ing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into access_level (user_id, role_id) values (?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
正如你可以看到Hibernate是試圖運行此查詢:
insert into access_level (user_id, role_id) values (?, ?)
從我的觀點。看起來好像hibernate沒有爲AccessLevel生成主鍵,即使我已經將@GeneratedValue添加到了id屬性。
注: 我在生產環境中使用PostgreSQL和環境,纔有發展與基於實體的描述開始時創建的所有模式HSQL數據庫工作。兩種環境都會產生同樣的問
問候, 克里斯蒂安科羅拉多