I have two tables Users and UserRoles. These are the entity class I have created,
@Entity
@Table(name="users")
public Users {
@Id
@Column(name = "id")
private Long userId;
@ManyToOne(cascade=CaseCadeType.ALL)
@JoinColumn("user_role_id")
private UserRole userRole;
@Column(name = "user_name")
private String userName;
}
@Entity
@Table(name="users_Roles")
public UsersRoles {
@Id
@Column(name = "user_role_id")
private Long userRoleId;
@Column(name = "user_role_name")
private String userRoleName;
}
Repository Class,
@Repository
public interface UsersRepository extends JpaRepository<Users ,Long>{
public List<Users> findByUserName(String userName);
}
For this I am able to get Json result like this.
[
{
"userid":"1",
"username":"user1",
"userrole": {
"userroleid":"1",
"userrolename":"ADMIN",
}
},
{
"userid":"2",
"username":"user2",
"userrole": {
"userroleid":"2",
"userrolename":"INTERN",
}
}
]
Instead of this can I get something like this..
[
{
"userid":"1",
"username":"user1",
"userrolename":"ADMIN",
},
{
"userid":"2",
"username":"user2",
"userrolename":"INTERN",
}
]
What changes I need to do in my entity class for getting only userrolename in result.
CodePudding user response:
I think you will need to create a getter for userrolename
:
public String getUserRoleName() {
return userRole.getUserRoleName();
}
To ignore unwanted fields, annotate them with @JsonIgnore
CodePudding user response:
You can try to use the @Converter annotation in your entity. However this way you will have the string (or preferably an enum) in your entity and this will produce your wanted json.
CodePudding user response:
you can achieve this using DTOs and modelMapper library :
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>current version</version>
</dependency>
public class UsersDTO {
String userid ;
String username ;
String userrolename ;
}
UsersDTo dto= modelMapper.map(user, UsersDto.class);
another way is to instantiate the dto class in your repo
@Query("SELECT new de.smarterco.example.dto.UsersDTO(u.id, u.username ,ur.name )
FROM Users u
join u.UsersRoles ur")
List<UsersDTO> findUsersDTo();
And the final way to do this is using jpa projection by creating your dto as interface
public intefaceUsersDTO {
String getuserid() ;
String username () ;
String userRoleName ();
}
and in your repo :
@Query("SELECT u.id , u.username ,ur.name as userRoleName )
FROM Users u
join u.UsersRoles ur")
List<UsersDTO> findUsersDTo();