gpt4 book ai didi

java - Spring Data JPA 用户帖子

转载 作者:行者123 更新时间:2023-12-01 11:25:31 25 4
gpt4 key购买 nike

我有用户登录和个人资料 View ,我希望用户有帖子。有人可以引导我走向正确的方向吗?

我有一个用户实体:

    @Entity
@Table(name = "usr", indexes = { @Index(columnList = "email", unique = true) })
// using usr because in may conflict with the name of the class
public class User {

public static final int EMAIL_MAX = 250;
public static final int NAME_MAX = 50;

/*
* public static enum Role {
*
* UNVERIFIED, BLOCKED, ADMINISTRATOR
*
* }
*/

// primary key long, needs to be annotated with @Id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

// add columns
@Column(nullable = false, length = EMAIL_MAX)
private String email;

@Column(nullable = false, length = NAME_MAX)
private String name;

// no length, the password will be encrypted to some longer value than the
// user enters
@Column(nullable = false)
private String password;

/*
* //email verification code
*
* @Column(length = 16) private String verificationCode;
*
* public String getVerificationCode() { return verificationCode; }
*
* public void setVerificationCode(String verificationCode) {
* this.verificationCode = verificationCode; }
*
*
* @ElementCollection(fetch = FetchType.EAGER) private Set<Role> roles = new
* HashSet<Role>();
*
*
*
* public Set<Role> getRoles() { return roles; }
*
* public void setRoles(Set<Role> roles) { this.roles = roles; }
*/

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public boolean isEditable() {
User loggedIn = MyTools.getSessionUser();

if (loggedIn == null) {
return false;
}

return loggedIn.getId() == id;
}

}

和仓库:

    public interface UserRepository extends JpaRepository<User, Long> {

// @Query("select u from User u where u.email = ?1")
User findByEmail(String email);

}

现在,为了让该用户发布帖子,我是否在 post pojo 中使用 @manytoone 创建一个帖子实体和存储库?我最终想创建一个推特,但首先我必须让用户发帖。如果您知道解释这一点的好教程,那就太好了。

最佳答案

创建第二个实体(java 类),例如用户帖子:

@Entity
@Table(...)
public class UserPost {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

private long userId;

...
}

然后将@OneToMany关系字段添加到User。级联、延迟加载等取决于您如何使用它。 User 内部看起来像这样:

@OneToMany(cascade={...})
@JoinColumn(name="userId")
private Set<UserPost> posts;

关于java - Spring Data JPA 用户帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30836946/

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