Reputation: 1
This is my session
String query = "from Authority";
session = sessionFactory.openSession();
List<Authority> authorities= session.createQuery(query).getResultList();
session.close();
for(Authority a: authorities){
System.out.println(a.getEmail());
}
This is my User class:
@Entity
@Table(name = "users")
public class User {
@Id
@NotBlank
@Size(max = 100)
@Email
@Column
private String email;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
private Set<Authority> authorities = new HashSet<>();
This is my Authority class:
@Entity
@Table(name = "authorities")
public class Authority {
@Id
@Column
private String authority;
@ManyToOne
@JoinColumn(name = "email")
private User user;
As I want to display my results I get a first row in every 'for' iteration. Do you have any idea why this is happening?
Let's say that in my database are rows like:
[email protected] ROLE_USER
[email protected] ROLE_USER
[email protected] ROLE_USER
[email protected] ROLE_USER
As a result of this "for" is:
[email protected]
[email protected]
[email protected]
[email protected]
Upvotes: 0
Views: 173
Reputation: 15861
There are several problems in the mapping.
The first problem is that authority
column in authorities
table is not a primary key. It is incorrect to mark it with Id
annotation and this confuses hibernate.
The second (and the main) problem is that according to you model each user may have several authorities but your data suggests that each Authority
may be related to many users. It seems that authorities
table models many-to-many relationship between User
and Authority
entities while the mapping tries to fit it into one-to-many relationship.
Upvotes: 1