Spring Data JPA user posts - java

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.

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;

Related

One to one relationship with hibernate annotation

I have this part of database schema:
and this User entity:
#Entity
#Table(name = "user", catalog = "ats")
public class User implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private String username;
private boolean enabled;
private Role role;
private ClientVersion clientVersion;
private ClientLicense clientLicense;
#JsonIgnore
private Set<NotificationHasUser> notificationHasUsers = new HashSet<NotificationHasUser>(0);
public User() {
}
public User(String username, boolean enabled) {
this.username = username;
this.enabled = enabled;
}
public User(String username, boolean enabled, Role role, Set<NotificationHasUser> notificationHasUsers) {
this.username = username;
this.enabled = enabled;
this.role = role;
this.notificationHasUsers = notificationHasUsers;
}
#Id
#Column(name = "username", unique = true, nullable = false, length = 45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "enabled", nullable = false)
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_role", nullable = false)
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_clientVersion", nullable = false)
public ClientVersion getClientVersion() {
return this.clientVersion;
}
public void setClientVersion(ClientVersion clientVersion) {
this.clientVersion = clientVersion;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user")
public Set<NotificationHasUser> getNotificationHasUser() {
return this.notificationHasUsers;
}
public void setNotificationHasUser(Set<NotificationHasUser> notificationHasUsers) {
this.notificationHasUsers = notificationHasUsers;
}
#OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
public ClientLicense getClientLicense(){
return this.clientLicense;
}
public void setClientLicense(ClientLicense clientLicense){
this.clientLicense = clientLicense;
}
}
All works fine until I add a new clientlicense. If I add this I receive an infinite loop:
Could not write content: Infinite recursion (StackOverflowError) (through reference chain: com.domain.User["clientLicense"]->com.domain.ClientLicense["user"]->com.domain.User["clientLicense"]->com.domain.ClientLicense["user"]->com.domain.User["clientLicense"]->com.domain.ClientLicense["user"]->com.domain.User["clientLicense"]->com.domain.ClientLicense["user"]->com.domain.User["clientLicense"]-....
This is my ClientLicense entity
#Entity
#Table(name = "clientlicense", catalog = "ats")
public class ClientLicense implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idClientLicense;
private Date startDate;
private Date endDate;
private int counter;
private String macAddress;
private String cpuId;
private User user;
public ClientLicense() {
}
/**
* #param startDate
* #param endDate
* #param counter
* #param macAddress
* #param cpuId
* #param users
*/
public ClientLicense(Date startDate, Date endDate, int counter, String macAddress, String cpuId, User user) {
super();
this.startDate = startDate;
this.endDate = endDate;
this.counter = counter;
this.setMacAddress(macAddress);
this.setCpuId(cpuId);
this.user = user;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id_clientLicense", unique = true, nullable = false)
public Integer getIdClientLicense() {
return this.idClientLicense;
}
public void setIdClientLicense(Integer idClientLicense) {
this.idClientLicense = idClientLicense;
}
#Column(name = "startDate", nullable = false)
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
#Column(name = "endDate", nullable = false)
public Date getEndDate() {
return this.endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Column(name = "counter", nullable = false)
public int getCounter() {
return this.counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
/**
* #return the macAddress
*/
#Column(name = "macAddress", nullable = false)
public String getMacAddress() {
return macAddress;
}
/**
* #param macAddress the macAddress to set
*/
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
/**
* #return the cpuId
*/
#Column(name = "cpuId", nullable = false)
public String getCpuId() {
return cpuId;
}
/**
* #param cpuId the cpuId to set
*/
public void setCpuId(String cpuId) {
this.cpuId = cpuId;
}
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "id_username")
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
}
This is my first OneToOne relationship, what is the correct annotation that I have to use? I read some example but I don't understand fine, they are different each other.
try something like this.
public class User {
private ClientLicense clientLicense;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
public ClientLicense getClientLicense() {
return this.clientLicense;
}
}
public class ClientLicense {
private User user;
#OneToOne
#JoinColumn(name = "id_username")
public User getUser() {
return this.user;
}
}
The problem is that the two entities have no way of finding out that the two fields are actually specifying a single relationship. So hibernate assumes that they are not the same relationship and therefore tries to fetch them (because one-to-one relationships are fetched eagerly by default).
Add #OneToOne(mappedBy = "user") before the clientLicense field in the User class to tell hibernate that this field is "mapped by" the same column as the user field in the ClientLicense class

Does Spring Save Relationship Data too in Rest Call?

So If I have a User and a UserRole Table like soo..
User Class
package app.repo.User;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#Version
private Long version;
#Column(nullable = false)
private String username;
#Column(nullable = false)
private String password;
#OneToMany(mappedBy = "user")
private Set<UserRole> roles;
protected User() {}
public User(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public String toString() {
return String.format(
"User[id=%d, username='%s', password='%s']",
id, username, password);
}
public long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
}
UserRole Class
package app.repo.User;
import javax.persistence.*;
#Entity
#Table(name = "user_roles")
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Version
private Long version;
#Column(name = "role_name")
private String roleName;
#ManyToOne
private User user;
public UserRole() {
}
public UserRole(String roleName, User user) {
this.roleName = roleName;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setUser(User user) {
this.user = user;
}
}
The above example has a oneToMany relationship with UserRole and a ManyToOne Relationship with user.
My first question is... is it possible to save User and UserRole in one save like so...
userDao.save(user);
And second question is. How would I set that up in a JSON post call ? and how would this be done. This is what I am doing now
{
"userId":"1",
"userName":"RestMan",
"password":"happy",
"version":"1",
"email":"restman#gmail.com",
"enabled":"1",
"roles": {
{"user":"1","role_name":"ROLE_COOLGUY"}
}
}
Otherwise I am thinking to just create a Model that saves the two separately in one method
Change the annotation like this : #OneToMany(cascade = CascadeType.ALL)

Add follow button in jsp spring data jpa

I have a User and Follower, I'm not very familiar with jsp and would like to add a follow button on the frontend and add the current user to the Follwers table and display follwers on the user profile which is already done.
How would I go about this?
Follower :
#Entity
public class Follower {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User:
#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;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private List<Tweets> tweets;
#OneToMany(mappedBy = "user")
private List<Follower> followers;
public List<Follower> getFollowers() {
return followers;
}
public void setFollowers(List<Follower> followers) {
this.followers = followers;
}
public List<Tweets> getTweets() {
return tweets;
}
public void setTweets(List<Tweets> tweets) {
Collections.reverse(tweets);
this.tweets = tweets;
}
public void setUsername(String username) {
this.username = username;
}
#Column(nullable = false)
private String username;
/*
* //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 String getUsername() {
return username;
}
}
Add a "Follow" button in JSP
<button id="follow_me">Follow</button>
Using JavaScript send the ajax call and send the user details to the controller and from the controller map it to POJO(Follower.java).
$('#follow_me').on('click',function(){
$.ajax(
url : url, // Controller URL
data : user_id, // Current User ID
follow_Flag : true,
success: function(result){
//Code for changing the view(JSP)
}});
);
});
And return the JSON to the user in the success call using below format and render it back to the JSP using JavaScript DOM Manipulation
{ userFollowFlag : true, // Current User Follow Flag
totalFollowers : 34 // Total count of followers
}

org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: core.user.User.userRole[core.user.UserRole]

I get this error with these entity classes. I've viewed this question, but I don't have a persistence.xml, so I'm unsure how to fix this. I'm building these entities with Dropwizard if that helps.
The problem seems to be with how I'm mapping a User to a UserRole. Both classes are in the same package.
User.java
#Entity
#Table(name = "USER")
public class User implements TimestampedItem {
//region Fields
protected String email;
protected String password;
protected String displayName;
protected Long ID;
protected Set<UserRole> userRole;
protected Boolean isActive = true;
protected Boolean isEmailConfirmed = false;
protected DateTime added = new DateTime();
protected DateTime modified = new DateTime();
//endregion
//region Constructors
public User() {
this("", "", "");
}
public User(String email, String password, String displayName) {
this(email, password, displayName, true);
}
public User(String email, String password, String displayName, Boolean isActive) {
this(email, password, displayName, new HashSet<>(), isActive, false);
}
public User(String email, String password, String displayName, Set<UserRole> userRole, Boolean isActive, Boolean isEmailConfirmed) {
this(email, password, displayName, userRole, isActive, isEmailConfirmed, new DateTime(), new DateTime());
}
public User(String email, String password, String displayName, Set<UserRole> userRole, Boolean isActive, Boolean isEmailConfirmed, DateTime added, DateTime modified) {
this.email = email;
this.password = password;
this.displayName = displayName;
this.userRole = userRole;
this.isActive = isActive;
this.isEmailConfirmed = isEmailConfirmed;
this.added = added;
this.modified = modified;
}
//endregion
//region Getters and Setters
/**
* Returns this Users email address
*
* #return this Users email address
*/
#Email
#Column(name = "EMAIL", unique = true, nullable = false, length = 255)
public String getEmail() {
return this.email;
}
/**
* Sets this Users email address
*
* #param email The email address to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Returns this User's password
*
* #return this User's password
*/
#Column(name = "PASSWORD", nullable = false, length = Passwords.DESIRED_KEY_LENGTH)
public String getPassword() {
return this.password;
}
/**
* Sets this User's password
*
* #param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Returns this User's unique User ID
*
* #return this User's unique User ID
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID", unique = true, nullable = false)
public Long getID() {
return this.ID;
}
/**
* Sets this User's unique User ID
*
* #param id The unique ID to set to this user
*/
public void setID(Long id) {
this.ID = id;
}
/**
* Whether this User's profile is isActive
*
* #return true if this User's profile is isActive, false otherwise
*/
#Column(name = "IS_ACTIVE", nullable = false)
public Boolean isActive() {
return this.isActive;
}
/**
* Sets whether this User's profile is isActive
*
* #param active true if this User's profile is isActive, false otherwise
*/
public void setActive(Boolean active) {
this.isActive = active;
}
/**
* Whether this User's email address has been confirmed.
* To confirm an email, they must click the activation link that is sent to their email address
*
* #return true if this User's email has been confirmed, false otherwise
*/
#Column(name = "IS_EMAIL_CONFIRMED", nullable = false)
public Boolean isEmailConfirmed() {
return this.isEmailConfirmed;
}
/**
* Sets whether this User's email address has been confirmed.
* To confirm an email, they must click the activation link that is sent to their email address
*
* #param isEmailConfirmed true if this User's email has been confirmed, false otherwise
*/
public void setEmailConfirmed(Boolean isEmailConfirmed) {
this.isEmailConfirmed = isEmailConfirmed;
}
/**
* Returns this User's display name
*
* #return this User's display name
*/
#Column(name = "DISPLAY_NAME", nullable = false)
public String getDisplayName() {
return this.displayName;
}
/**
* Sets this User's display name
*
* #param displayName The display name to associate with this User
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
public Set<UserRole> getUserRole() {
return this.userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
#Override
#Column(name = "ADDED", nullable = false)
public DateTime getAdded() {
return this.added;
}
#Override
public void setAdded(DateTime added) {
this.added = added;
}
#Override
#Column(name = "MODIFIED", nullable = false)
public DateTime getModified() {
return this.modified;
}
#Override
public void setModified(DateTime modified) {
this.modified = modified;
}
//endregion
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
// These probably aren't needed, since a user is considered unique by ID alone
// if (!displayName.equals(user.displayName)) return false;
// if (!email.equals(user.email)) return false;
// if (!password.equals(user.password)) return false;
return getID().equals(user.getID());
}
#Override
public int hashCode() {
int result = email.hashCode();
result = 31 * result + password.hashCode();
result = 31 * result + displayName.hashCode();
return result;
}
}
UserRole.java
#Entity
#Table(
name = "user_roles"
, uniqueConstraints = #UniqueConstraint( columnNames = { "role", "USER_ID" } )
)
public class UserRole{
private Integer userRoleId;
private User user;
private String role;
public UserRole() {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_role_id", unique = true, nullable = false)
public Integer getUserRoleId() {
return this.userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "role", nullable = false, length = 45)
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
}
Did you set up your HibernateBundle properly? Dropwizard Hibernate offers two bundles to set up the persistence unit with hibernate, one being the default HibernateBundle which needs all entity classes passed in the constructor - are both classes passed in?
Alternatively you can use ScanningHibernateBundle and pass in the package name of your entities as String so you don't miss anything in the future. This would look like this in your Application:
private final HibernateBundle<MyConfiguration> hibernate =
new ScanningHibernateBundle<MyConfiguration>("com.acme.entity") {
#Override
public DataSourceFactory getDataSourceFactory(MyConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
are you use spring frame ? If you use this,you can add this code into appliactionContext.xml
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="dbke" />
<property name="PersistenceXmlLocation" value="classpath:META-INF/jpa-persistence.xml" />
</bean>
you need create jpa-persistence.xmlfirstly.For example:
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="dbke" transaction-type="RESOURCE_LOCAL">
<class>core.user.Userrole</class>
<class>core.user.User</class>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
</persistence-unit>
</persistence>

How To Define a JPA Repository Query with a Join

I would like to make a Join query using Jpa repository with annotation #Query.
I have two tables:
table user
with iduser,user_name
and:
table area
with idarea, area_name and iduser
The native query is:
SELECT
u.user_name
FROM
user as u
INNER JOIN area as a ON a.iduser = u.iduser
WHERE
a.idarea = 4
Now I have a Table Hibernate entity
User and Area
So I tried with UserRespository
#Query(SELECT u.userName FROM User u
INNER JOIN Area a ON a.idUser = u.idUser
WHERE
a.idArea = :idArea)
List<User> findByIdarea(#Param("idArea") Long idArea);
The Log says:
unexpected token:
Any Idea, please?
My table Entity
#User Table
#Entity
#Table(name="user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long idUser;
private String userName;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="iduser")
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
#Column(name="user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
#AREA table
#Entity
#Table(name="area")
public class Area implements Serializable {
private static final long serialVersionUID = 1L;
private Long idArea;
private String areaName;
private Long idUser;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="idarea")
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
#Column(name="area_name")
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
#Column(name="iduser")
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
}
You are experiencing this issue for two reasons.
The JPQL Query is not valid.
You have not created an association between your entities that the underlying JPQL query can utilize.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="iduser")
private Long idUser;
#Column(name="user_name")
private String userName;
#OneToOne()
#JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your #Query declaration. The query specified in your #Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
#Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
#Entity
#Table(name = "area")
public class Area {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="idarea")
private Long idArea;
#Column(name="area_name")
private String areaName;
#OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

Categories

Resources