Это мои таблицы:
Код: Выделить всё
CREATE TABLE user (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(50) NOT NULL,
enabled BOOLEAN DEFAULT TRUE
);
CREATE TABLE authority (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
authority VARCHAR(50) UNIQUE NOT NULL
);
CREATE TABLE user_authority (
user_id BIGINT,
authority_id BIGINT,
PRIMARY KEY (user_id, authority_id),
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE,
FOREIGN KEY (authority_id) REFERENCES authority(id) ON DELETE CASCADE
);
Код: Выделить всё
@Entity
@Data
@Builder
@Table(name = "user", schema = "user_database")
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
private String password;
private boolean enabled;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.ALL})
@JoinTable(
name = "user_authority",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "authority_id")
)
private Set authority;
}
@Data
@Entity
@Builder
@Table(name = "authority", schema = "user_database")
@NoArgsConstructor
@AllArgsConstructor
public class AuthorityEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String authority;
@ToString.Exclude
@ManyToMany(mappedBy = "authority")
private Set users;
}
SERVICE:
public Response createUser(UserEntity user) {
UserEntity saveUserEntity = userRepository.save(userEntity);
log.info(saveUserEntity.toString());
return new Response(200, "SUCCESS", saveUserEntity.toString());
}
REPOSITORY:
@Repository
public interface UserRepository extends JpaRepository {
UserEntity findByUsername(String username);
}
Таблица USER
Код: Выделить всё
d, username, password
1, userA, 1234
2, userB, 4321
Код: Выделить всё
id, authority
1, READ
2, WRITE
Код: Выделить всё
user_id, authority_id
1, 1
1, 2
2, 1
- CascadeType.ALL — после сохранения пользователя A, когда я пытаюсь сохранить пользователя B, я получаю следующую ошибку:
- CascadeType.MERGE, CascadeType.ALL — тот же результат, что и в пункте 1.
CascadeType.MERGE — после сохранения пользователя A при попытке сохранить пользователя B я получаю следующую ошибку:
Я также пробовал использовать PERSIST в разных вариантах. Все равно не повезло.
Подробнее здесь: https://stackoverflow.com/questions/790 ... ild-entity