I'm creating a Spring-boot application using jhipster where users have moneyAccounts. Currently when a user logs onto the application they can see all moneyAccounts for all users, and I am adding a method that will find only accounts for the currently logged in user. How do I formulate a query that will only find accounts based on the currently logged in user?
I have tried a query similar to the one in this post but my build would not run unless I used the native query format. I reformulated the query in native format as shown below.
@Query(value = "select * from MONEY_ACCOUNT where MONEY_ACCOUNT.USER_DETAILS_ID = ?#{principal?.id}", nativeQuery = true)
List<MoneyAccount> findByUserIsCurrentUser();
The above query generated a 500 error on my page. Any advise is welcome!
Entity:
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 6)
@Column(name = "lang_key", length = 6)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
//getters and setters etc.
Repository:
@Repository
public interface MoneyAccountRepository extends JpaRepository<MoneyAccount, Long> {
@Query(value = "select * from MONEY_ACCOUNT where MONEY_ACCOUNT.USER_DETAILS_ID = #{principal.id}", nativeQuery = true)
List<MoneyAccount> findByUserIsCurrentUser();
}