gpt4 book ai didi

java - 在ManyToMany表, hibernate , Spring 中保存数据的问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:03 24 4
gpt4 key购买 nike

下面-父表-用户:

@Entity
@Table(name = "user")
public class User {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "username", length = 50, unique = true)
@NotNull
@Size(min = 4, max = 50)
private String username;

@Column(name = "password", length = 100)
@NotNull
@Size(min = 4, max = 100)
private String password;

@ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
@JoinTable(
name = "user_role",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
private List<Role> roles;


//constructor, getters/setters


在下面您可以找到带有角色的表:

@Entity
@Table(name = "role")
public class Role {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name", length = 50)
@NotNull
@Enumerated(EnumType.STRING)
private RoleName name;

@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
private List<User> users;

//constructor, getters/setters


我将尝试通过以下方法保存用户:

private static SessionFactory sessionFactory;
private Session session;


@Override
public void saveUser(User user) {
Role role = getRoleByName(RoleName.ROLE_ADMIN);
user.getRoles().add(role );
role.getUsers().add( user );
session.persist(user);
}

public Role getRoleByName(RoleName name) {

Query query = session.createQuery("SELECT r FROM Role r WHERE r.name= :name");
query.setParameter("name", name);
return (Role) query.uniqueResult();
}


但是我有两个问题:
-首先-主要问题-我做错了事,无法保存新用户。
-第二个-我在getRoleByName的查询结果中没有null结果,但是当然,该角色存在于表user_roles中。

任何解决方案对我来说都是完美的。

先感谢您。

最佳答案

好的,目前的情况很酷!

@Override
public void saveUser(User user) {
Session currentSession = entityManager.unwrap(Session.class);
Role role = getRoleByName(RoleName.ROLE_ADMIN);
user.getRoles().add(role );
role.getUsers().add( user );
currentSession.persist(user);
}

public Role getRoleByName(RoleName name) {
Session currentSession = entityManager.unwrap(Session.class);
Query query = currentSession.createQuery("SELECT r FROM Role r WHERE r.name= :name");
query.setParameter("name", name);
return (Role) query.uniqueResult();
}


但是仍然不要保存到数据库。没有错误。任何想法?

关于java - 在ManyToMany表, hibernate , Spring 中保存数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56841961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com