MOXy. generate JSON, doesn't contain reference class - json

I used Eclipselink MOXy to convert my POJO(using JPA) to json. and it's work.
but i have one problem. I have pojo class MAccount contain many to one relation to class MProduct,. when I convert to json, result show that class MAccount not in class MProduct.
here my class MAccount implementation:
#XmlRootElement
#Entity
#Table(name="m_account")
public class MAccount extends BaseObject implements Serializable {
private static final long serialVersionUID = UUID.randomUUID().getMostSignificantBits();
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#XmlID
private Long id;
#Column(name="account_id")
private String accountId;
#Column(name="card_number")
private String cardNumber;
//bi-directional many-to-one association to Product
#ManyToOne
#JoinColumn(name="m_product_id")
#XmlIDREF
private MProduct mProduct;
public MCustomerAccount() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountId() {
return this.accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public MProduct getMProduct() {
return this.mProduct;
}
public void setMProduct(MProduct mProduct) {
this.mProduct = mProduct;
}
// Imlement base object method
...
}
here my class MProduct implementation:
#XmlRootElement
#Entity
#Table(name="m_product")
public class MProduct extends BaseObject implements Serializable {
private static final long serialVersionUID = UUID.randomUUID().getMostSignificantBits();
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#XmlID
private Long id;
#Column(name="product_code")
private String productCode;
#Column(name="product_name")
private String productName;
//bi-directional many-to-one association to MAccount
#OneToMany(mappedBy="mProduct")
#XmlInverseReference(mappedBy="mProduct")
private Set<MAccount> mAccountList;
public MProduct() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Set<MAccount> getMAccountList() {
return this.mAccountList;
}
public void setMAccountList(Set<MAccount> mAccountList) {
this.mAccountList = mAccountList;
}
// Imlement base object method
...
}
And generate JSON from MAccount class
{"MAccount":[
{"#type":"mAccount","id":"6","accountId":"05866039901"},
{"#type":"mAccount","id":"7","accountId":"25600036290"}]
}
there is no MProduct in there, the correct json result should be like below
{"MAccount":[
{"#type":"mAccount","id":6,"accountId":"05866039901","MProduct":{"#type":"mProduct","productCode":"T01","productName":"Book"}},
{"#type":"mAccount","id":7,"accountId":"25600036290","MProduct":{"#type":"mProduct","productCode":"T02","productName":"Pen"}}]
}
Is Anyone know how to solve this problem
Thank's b4

Because you are annotating the field, there is a chance that JPA has not populated that field yet due to lazy loading. If you annotate the property (get/set) instead do you still see this behaviour?
For more information on #XmlInverseReference see:
http://bdoughan.blogspot.com/2010/07/jpa-entities-to-xml-bidirectional.html

Related

JAVA Spring boot how to post arraylist in Postman

I am trying to save some books via request but I am getting errors. How do I exactly do this? This is the model
#Entity
public class Reservation {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String user;
private int period;
#OneToMany
private List<Books> books;
public static String error () {
return "Input error";
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getPeriod() { return period;}
public void setPeriod(int period) {this.period = period;}
public List<Books> getBooks() { return books;}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#Entity
public class Books implements Serializable {
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
private int id;
private String name;
}
}
Controller:
#PostMapping("/reserveBook")
public String reserveBook(#RequestBody Reservation reservation)
{
if (reservation.getPeriod() > 2)
return Book.error();
else{
reserveRepo.save(reservation);
return "success";
}
}
Tried json like this
{
"user": "Jason",
"books":[{"name": "Wonders"}, {"name": "Good classics"}],
"period": 2
}
What exact error you are getting? Can you try to make your inner class static? Like
public static class Books implements Serializable

No adding entity in a manytoone relationship using spring boot and jpa

I'm new in spring boot, I'm looking for help with this problem: I have two entities connected by a ManytoOne relationship. The entities are course and professor.
The professor Entity:
#Entity
#Table(name = "professor")
public class Professor implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idProfessor;
private String name;
private String lastName;
private String phone;
private String mail;
#Fetch(FetchMode.JOIN)
#OneToMany(mappedBy = "professor", cascade= CascadeType.ALL)
private List<Course> courses;
public Professor() {
}
public Long getIdProfessor() {
return idProfessor;
}
public void setIdProfessor(Long idProfessor) {
this.idProfessor = idProfessor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
The Course Entity:
#Entity
#Table(name = "course")
public class Course implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idCourse;
private String title;
private String description;
#ManyToOne
#JoinColumn(name="professor_id")
private Professor professor;
#ManyToMany(mappedBy = "courses")
private List<Student> students;
public Course() {}
public Long getIdCourse() {
return idCourse;
}
public void setIdCourse(Long idCourse) {
this.idCourse = idCourse;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I also created a rest controller to create Course and I defined POST endpoint like this:
#PostMapping(value="/create")
public Course createCourse(#RequestBody Course course) {
return courseRepo.save(course);
}
When I add a new course in postman, the course is added but it is not assigned to the corresponding professor (an existing professor in the database), "idProfessor" is always assigned to NULL. Here is an example of POST API execution in postman and the result in MySQL.
postman
mysql
Any suggestions?

Spring Boot: How to retrieve the username by user_id?

I have already connected my springboot to MySQL database. I want to display the username when user_id is specified in the HTTP request. e.g. http://8080/user/1 must display the name of the user with user_id 1.
The table contains attributes as:
| Integer user_id; | String username; | String fathername; | String mothername;
I have already tried this code in by Controller class but i does not seem to be working
#RequestMapping("/{userid}")
#ResponseBody
public String getById(Integer userid) {
String name="";
try {
Optional<Persondetails> persondetails=persondetailsRepository.findById(personid);
name = String.valueOf(userdetails.getName());
}
catch (Exception ex) {
return "Name not found";
}
return "The Name of the user is : " + name;
}
my repository code:
import java.util.List;
import java.util.Optional;
public interface UserdetailsRepository extends JpaRepository<Userdetails, Integer> {
public Optional<Userdetails> findById(Integer userid);
}
It says getName() is undefined for the type Optional
But i have defined it in Userdetails class
public class Userdetails {
#Id
#GeneratedValue
#Column(name="user_id")
private Integer userid;
#Column(name="name")
private String name;
#Column (name="fathers_name")
private String fathersname;
#Column(name="mothers_name")
private String mothersname;
public Userdetails() {
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getFathersname() {
return fathersname;
}
public void setFathersname(String fathersname) {
this.fathersname = fathersname;
}
public void setMothersname(String mothersname) {
this.mothersname = mothersname;
}
public String getMothersname() {
return mothersname;
}
}
It's missing the method type GET, you can do by two options:
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User findOne(#PathVariable("id") int id){
return userService.findById(id);
}
OR
#GetMapping("/{id}")
public String getString(#PathVariable("id") int id) {
return "Helloworld";
}
Spring boot Connect with Mysql and get Data.
application.properties
server.contextPath=/demo-user
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
*Controller.Java
#RequestMapping({"/users"})
public class UserController {
#Autowired
private UserService userService;
#GetMapping(path = {"/{id}"})
public User findOne(#PathVariable("id") int id){
return userService.findById(id);
}
}
UserService.java
public interface UserService {
User findById(int id);
}
UserServiceImpl.java
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository repository;
#Override
public User findById(int id) {
return repository.findOne(id);
}
}
UserRepository .java
public interface UserRepository extends Repository<User, Integer> {
User findOne(int id);
}
User.java
#Entity
#Table(name = "user")
public class User {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
//setter and getter
}
Make request from browser or application.
http://localhost:8080/demo-user/users/1

How to count row table in JPA Query

I'm new to Spring Boot. I have a mysql database, I use a query to count row in my table. But it's not work, it still return my original table data. Can you help me check my code.
Here is my Entity:
#Entity
#Table(name = "act_id_membership", schema = "activiti", catalog = "")
#IdClass(ActIdMembershipEntityPK.class)
public class ActIdMembershipEntity {
private String userId;
private String groupId;
#Id
#Column(name = "USER_ID_")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Id
#Column(name = "GROUP_ID_")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActIdMembershipEntity that = (ActIdMembershipEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
Here is my query:
#Repository
public interface MemershipRepository extends JpaRepository<ActIdMembershipEntity, String> {
#Query ("select new com.example.activiti_restful.dtos.UserMembership(i.userId, count(i)) from ActIdMembershipEntity i where i.userId ='kermit'")
UserMembership countMemberships(String userId);
}
Updated code:
My service class:
#Service
public class MembershipService {
#Autowired
private MemershipRepository repository;
public long count() {
return repository.count();
}
My resource class:
#RestController
public class MembershipResource {
#Autowired
private MembershipService membershipService;
#GetMapping("/membership")
public long list() {return membershipService.count();}
}
My custom JSON Object class:
public class UserMembership {
private String userId;
private long numberOfusers;
public UserMembership(String userId, long numberOfusers) {
this.userId = userId;
this.numberOfusers = numberOfusers;
}
}
MySQL Table:
act_id_membership
According repositories documentation using CrudRepository provides a method called count() that is one of the Superinterfaces which JpaRepository is implemented.
Based CrudRepository documentation says:
long count(); Returns the number of entities.
Then you should use CrudRepository method. In addition Remove Uppercase MembershipREPOSITORY, by java code convention, you have to use by following way MembershipRepository.
#Repository
public interface MembershipRepository extends JpaRepository <ActIdMembershipEntity, String> {
}
And use it in your Service:
#Service
public class MembershipService {
#Autowired
private MembershipRepository repo;
public long count() {
return repo.count();
}
}
UPDATED
Based on your requirement:
In Controller:
#RestController
public class MembershipResource {
#Autowired
private MembershipService membershipService;
#GetMapping("/membership")
public List<Object> list() { return membershipService.countMemberships();
}
}
In Service:
#Service
public class MembershipService {
#Autowired
private MemershipRepository repository;
public List<Object> countMemberships() {
return repository.countMemberships();
}
}
In Repository:
#Repository
public interface MemershipRepository extends JpaRepository<ActIdMembershipEntity, String> {
#Query ("select i.userId, count(i) from ActIdMembershipEntity i where i.userId ='kermit'")
List<Object> countMemberships();
}
*> Actually I want it return a json format like [{ name: kermit, value:6}]. Now it just return a number 6 only. How I can do that? Thank you!
First, create a class to wrap your data:
public class UserMembership {
private String userId;
private long numberOfUsers;
public UserMembership(String userId, long numberOfUsers) {
this.userId = userId;
this.numerOfUsers = numberOfUsers;
}
}
Then
#Repository
public interface MembershipRepository extends JpaRepository <ActIdMembershipEntity, String> {
#Query ("select new *****.UserMembership(i.userId, count(i)) from ActIdMembershipEntity i where i.userId = :userId")
UserMembership countMemberships(String userId);
}
*****: your full package name
Hope it help!

Annotation for binding a json field to a field in POJO with a different name

Java class (used as a Data Transfer Object):
class Resource also has a field named id with a different type along with its getter and setter, hence the syntax error.
class A extends Resource
{
private int id;
public int getId() { return id; } // syntax error as getId() function already exists in Resource
public void setId(int id) { this.id = id; }
}
Since the above class is a DTO, a JSON response (with field id) will be mapped to it, and getId() cannot be used, I want to change the field to _id_ and change getter and setter correspondingly, and mark it with an annotation saying bind this to id field.
Note: I'm using spring boot. I tried using #JsonProperty annotation but that didn't work. Is there an annotation for doing this in spring?
Googled and found this question: Jackson serialization: how to ignore superclass properties. Adapted it for your problem.
public class A extends B {
private int id;
public A(int id) {
super.setId("id" + id);
this.id = id;
}
#Override
#JsonProperty("_id_")
public String getId() {
return super.getId();
}
#Override
#JsonProperty("_id_")
public void setId(String id) {
super.setId(id);
}
#JsonProperty("id")
public int getIntId() {
return id;
}
#JsonProperty("id")
public void setIntId(int id) {
this.id = id;
}
}
public class B {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Tested it with this:
#RestController
public class TestController {
#GetMapping("/test")
public A test() {
return new A(1);
}
}
And the output was:
{
"_id_": "id1",
"id": 1
}
public A extends Resource {
private int id;
#JsonProperty("_id")
public int getId() {
return id;
}
#JsonProperty("id")
public void setId(int id) {
this.id = id;
}
}
the method names should be different, so jackson parses it as different fields, not as one field.