Reputation: 1189
I have user login and profile view, I would like the users to have posts. Can someone guide me in the right direction?
I have a user entity:
@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;
}
}
and repo:
public interface UserRepository extends JpaRepository<User, Long> {
// @Query("select u from User u where u.email = ?1")
User findByEmail(String email);
}
now, in order to have posts by that user, do I create a posts entity and repository with @manytoone in post pojo? I'm trying to make a twitter eventually but first I gotta get users to post. If you know of a good tutorial explaining this then that'd be great.
Upvotes: 0
Views: 555
Reputation: 574
Create a second entity (java class) e.g. UserPost:
@Entity
@Table(...)
public class UserPost {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long userId;
...
}
Then add @OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User:
@OneToMany(cascade={...})
@JoinColumn(name="userId")
private Set<UserPost> posts;
Upvotes: 1