Convert Java nested class to JSON using JAX-RS - java

I basically want to send an object of class Customer as JSON to android from my JAVA REST API.
My Customer class looks like this:
public class Customer {
private long customerId;
private String firstName;
private String middleName;
private String lastName;
private String gender;
private long accountId;
class Account {
private long accountId;
private int balance;
}
}
The JSON I am expecting should look like this:
{
"customerId": "something",
"firstName": "something",
"middleName": "something",
"gender": "M or F",
"accountId": "something",
"Account": {
"accountId": "something",
"balance": "something",
}
}
Extra Information:
I use this dependency for conversion to JSON.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
How can I make an object of this class so that it's JSON conversion by JAX-RS look like this?

Outer class could have more than one inner class instance. If you want to marshall it to JSON, you should tell, what instance to use. For this, I suppose to add Account account field into outer class. Then, you need to add getters/setters for private fields and XmlElement annotations. Finally, it will look like this:
import javax.xml.bind.annotation.XmlElement;
public class Customer {
private long customerId;
private String firstName;
private String middleName;
private String lastName;
private String gender;
private long accountId;
private Account account;
class Account {
private long accountId;
private int balance;
#XmlElement(name = "accountId")
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
#XmlElement(name = "balance")
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
#XmlElement(name = "customerId")
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
#XmlElement(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#XmlElement(name = "middleName")
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#XmlElement(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#XmlElement(name = "gender")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#XmlElement(name = "accountId")
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
#XmlElement(name = "account")
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
Now, you could use instances of this class with Jersey client like this:
Entity e = Entity.entity(customer, "application/json");
Response r = invocationBuilder.method("POST", e);

Related

Unable to retrieve data from MySQL using Spring boot JPA

I am getting a java.lang.NullPointerException error at the line where the program begins to retrieve data from the database, specifically starting with the code recordDB.setAccountName(billing.getAccountId().getAccountName());. The entity tables are joined together and at first I thought that it can't retrieve data from other other tables but I tried to run with just recordDB.setAmount(billing.getAmount()); Can someone explain what I missed or is there something wrong with the logic?
Component
#Component
public class FileProcessor {
#Autowired
private BillingRepository billingRepository;
public FileProcessor() {
}
public List<Record> retrieveRecordfromDB(List<Request> requests) throws BarsException{
List<Record> records = new ArrayList<>();
if (!requests.isEmpty()) {
for (Request request : requests) {
Billing billing = billingRepository
.findByBillingCycleAndStartDateAndEndDate(
request.getBillingCycle()
, request.getStartDate()
, request.getEndDate());
if (billing == null) {
throw new BarsException(BarsException.NO_RECORDS_TO_WRITE);
}
Record recordDB = new Record();
recordDB.setBillingCycle(request.getBillingCycle());
recordDB.setStartDate(request.getStartDate());
recordDB.setEndDate(request.getStartDate());
recordDB.setAccountName(billing.getAccountId().getAccountName());
recordDB.setFirstName(billing.getAccountId().getCustomerId().getFirstName());
recordDB.setLastName(billing.getAccountId().getCustomerId().getLastName());
recordDB.setAmount(billing.getAmount());
records.add(recordDB);
}
}
return records;
}
}
Account Entity
#Entity
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "account_id")
private int accountId;
private String accountName;
private LocalDateTime dateCreated;
private String isActive;
private String lastEdited;
public Account() {
}
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public String getLastEdited() {
return lastEdited;
}
public void setLastEdited(String lastEdited) {
this.lastEdited = lastEdited;
}
public Customer getCustomerId() {
return customerId;
}
public void setCustomerId(Customer customerId) {
this.customerId = customerId;
}
public Set<Billing> getBilling() {
return billing;
}
public void setBilling(Set<Billing> billing) {
this.billing = billing;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "customer_id")
private Customer customerId;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "account_id")
private Set<Billing> billing;
}
Billing Entity
#Entity
public class Billing {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "billing_id")
private int billingId;
//private int billingId;
private int billingCycle;
private String billingMonth;
private Double amount;
private LocalDate startDate;
private LocalDate endDate;
private String lastEdited;
//private Account accountId;
public Billing() {
}
public int getBillingId() {
return billingId;
}
public void setBillingId(int billingId) {
this.billingId = billingId;
}
public int getBillingCycle() {
return billingCycle;
}
public void setBillingCycle(int billingCycle) {
this.billingCycle = billingCycle;
}
public String getBillingMonth() {
return billingMonth;
}
public void setBillingMonth(String billingMonth) {
this.billingMonth = billingMonth;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public String getLastEdited() {
return lastEdited;
}
public void setLastEdited(String lastEdited) {
this.lastEdited = lastEdited;
}
public Account getAccountId() {
return accountId;
}
public void setAccountId(Account accountId) {
this.accountId = accountId;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "account_id")
private Account accountId;
}
Customer Entity
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "customer_id")
private int customerId;
private String firstName;
private String lastName;
private String address;
private String status;
private LocalDateTime dateCreated;
private String lastEdited;
public Customer() {
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public String getLastEdited() {
return lastEdited;
}
public void setLastEdited(String lastEdited) {
this.lastEdited = lastEdited;
}
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "customer_id")
private Set<Account> account;
}
Repository
#Repository
public interface BillingRepository extends JpaRepository<Billing, Integer> {
public Billing findByBillingCycleAndStartDateAndEndDate (int billingCycle, LocalDate startDate, LocalDate endDate);
}
Your naming is unintuitive, which hinders people unfamiliar with the code:
recordDB implies that it is the Database for records. Instead, it is a record that is to be saved in the DB. Naming it "RecordToSave" or similar is much better, since it gets the intention across.
getAccountId() implies that the id of an account is returned (an int or long) NOT that the account itself is returned. You should rename it to getAccount()
About the issue:
What you are using as a bidirectional ManyToOne <-> OneToMany relationship.
One side should be the owning side of the relationship. Here the #JoinColumn should be stated. The receiving end should have a MappedBy Property.
See this guide for more information: https://thorben-janssen.com/hibernate-tips-map-bidirectional-many-one-association/
It should solve the issue, since only the data retrieval for connected tables does not seem to work, hence fixing the references should fix the issue.
Your billing.getAmount() does refer to data written in the billing object/table, and is not from another table like billing.getAccountId().getAccountName() which gets data from the account table connected to the billings table.
Last, but not least:
Think about your cascading strategy. The way it currently works, deleting a billing will delete the account of that billing, which deletes all references made there and so on since you currently use Cascade.All for ALL entries. This is bad.
Here is a guide for cascading: https://howtodoinjava.com/hibernate/hibernate-jpa-cascade-types/
Are you sure the field names in the Billing class exactly match the database column names? I see you set the column name to "billing_id" explicitly for the id field, but not for any other fields. My guess is that the fields in that class are all null since there are no corresponding database columns (debug to confirm).

When I save an Entity with hibernate the foreign key is not saved always an null

I have two classes User.java and Vehicle.java with OneToMany relationship. When I post via postman a user with 2 vehicles, the data is stored correctly in the DB but the foreign key in the Vehicles table is stored always as null.
User.java
#Entity
#Table(name = "users", schema = "vehicleproject")
public class User {
#Id
#Column(name = "user_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "address")
private String address;
#Column(name = "afm")
private int afm;
#Column(name = "role_id")
private UserType type;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Vehicle> vehicles = new ArrayList<>();
public User(){}
public User(long id, String email, String password, String firstName, String lastName, String address, int afm, UserType type, List<Vehicle> vehicles) {
this.id = id;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = vehicles;
}
public User(long id, String email, String password, String firstName, String lastName, String address, int afm, UserType type) {
this.id = id;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = new ArrayList<>();
}
public User(String email, String password, String firstName, String lastName, String address, int afm, UserType type, List<Vehicle> vehicles) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = vehicles;
}
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAfm() {
return afm;
}
public void setAfm(int afm) {
this.afm = afm;
}
public UserType getType() {
return type;
}
public void setType(UserType type) {
this.type = type;
}
public void addVehicleToList(Vehicle vehicle){
this.vehicles.add(vehicle);
}
public void removeVehicleFromUserList(Vehicle vehicle){
this.vehicles.remove(vehicle);
}
}
Vehicle.java
#Entity
#Table(name = "vehicles", schema = "vehicleproject")
public class Vehicle {
#Id
#Column(name = "vehicle_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "brand")
private String brand;
#Column(name = "model")
private String model;
#Column(name = "creation_date")
private LocalDate creationDate;
#Column(name = "color")
private String color;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
#Column(name = "plate_number")
private String plateNumber;
public Vehicle(){
}
public Vehicle(long id, String brand, String model, LocalDate creationDate, String color, User user, String plateNumber) {
this.id = id;
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.user = user;
this.plateNumber = plateNumber;
}
public Vehicle(String brand, String model, LocalDate creationDate, String color, User user, String plateNumber) {
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.user = user;
this.plateNumber = plateNumber;
}
public Vehicle(long id, String brand, String model, LocalDate creationDate, String color, String plateNumber) {
this.id = id;
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.plateNumber = plateNumber;
}
public String getPlateNumber() {
return plateNumber;
}
public void setPlateNumber(String plateNumber) {
this.plateNumber = plateNumber;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public LocalDate getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDate creationDate) {
this.creationDate = creationDate;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
#JsonIgnore
public User getUser() {
return user;
}
#JsonProperty
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vehicle vehicle = (Vehicle) o;
return id == vehicle.id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
My json payload is:
{
"email": "new#player7.com",
"password": "newplayer2",
"firstName": "ithList",
"lastName": "Constructor",
"address": "Ermou 20",
"afm": 1005733537,
"type": "USER",
"vehicles": [
{
"brand": "MASSERATI",
"model": "GOD",
"creationDate": "2015-05-05",
"color": "WHITE",
"plateNumber": "Amm2421"
},
{
"brand": "Toyota",
"model": "Corolla",
"creationDate": "2015-05-05",
"color": "WHITE",
"plateNumber": "Fmmf2421"
}
]
}
I see this in my spring boot app it inserts all the data for User generating an Id for the new User.
It also inserts all the data for vehicles generating new Ids for Vehicles but in the FK column in Vehicles it inserts null always:
2020-07-12 15:55:20.169 TRACE 14700 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [BIGINT] - [null]
RestController method for inserting a User:
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public User insert(#RequestBody User user) {
return userService.save(user);
}
#KavithakaranKanapathippillai the solution that you proposed is working!
"add this user.getVehicles().forEach(vehicle -> vehicle.setUser(user)); before return userService.save(user);"
But I cannot Understand since it is a Json with vehcles inside the User Object why it is not working directly?
Try to remove #Json from methods getUser and setUser and from field User user, and add to your json the user id:
"user": {"id" = 1}

How to map JSONObject in Java object

I have to map this JSONObject into a Java object.
This is my Json:
{"WALLET":{
"ID":"1234",
"BAL":"20.000",
"NAME":"Filomena",
"EMAIL":"filo#gmail.com",
"DOCS":[
{
"ID":"001",
"S":"0",
"TYPE":"CardId",
"VD":"2019"
}
],
"IBANS":[
{
"ID":"001",
"S":"1",
"DATA":"iban",
"SWIFT":"swiftCode",
"HOLDER":"holder"
}
],
"STATUS":"string",
"BLOCKED":"1",
"SDDMANDATES":[
{
"ID":"sddMandateId",
"S":"status",
"DATA":"iban",
"SWIFT":"swiftCode"
}
],
"LWID":"string",
"CARDS":[
{
"ID":"string",
"EXTRA":{
"IS3DS":"string",
"CTRY":"string",
"AUTH":"string",
"NUM":"string",
"EXP":"string",
"TYP":"string"
}
}
],
"FirstName":"string",
"LastName":"string",
"CompanyName":"string",
"CompanyDescription":"string",
"CompanyWebsite":"string"
}
}
This is my Java class:
public class Wallet {
private String id;
private String bal;
private String name;
private String email;
private List<Doc> docs;
private List<Iban> ibans;
private String status;
private String blocked;
private List<SddMandate> sddMandates ;
private String lwid;
private List<Card> cards;
private String firstName;
private String lastname;
private String companyName;
private String companyDescription;
private String companyWebSite;
public Wallet(){
}
public Wallet(String id, String bal, String name, String email, List<Doc> docs, List<Iban> ibans, String status,
String blocked, List<SddMandate> sddMandates, String lwid, List<Card> cards, String firstName,
String lastname, String companyName, String companyDescription, String companyWebSite) {
super();
this.id = id;
this.bal = bal;
this.name = name;
this.email = email;
this.docs = docs;
this.ibans = ibans;
this.status = status;
this.blocked = blocked;
this.sddMandates = sddMandates;
this.lwid = lwid;
this.cards = cards;
this.firstName = firstName;
this.lastname = lastname;
this.companyName = companyName;
this.companyDescription = companyDescription;
this.companyWebSite = companyWebSite;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBal() {
return bal;
}
public void setBal(String bal) {
this.bal = bal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
public List<Iban> getIbans() {
return ibans;
}
public void setIbans(List<Iban> ibans) {
this.ibans = ibans;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBlocked() {
return blocked;
}
public void setBlocked(String blocked) {
this.blocked = blocked;
}
public List<SddMandate> getSddMandates() {
return sddMandates;
}
public void setSddMandates(List<SddMandate> sddMandates) {
this.sddMandates = sddMandates;
}
public String getLwid() {
return lwid;
}
public void setLwid(String lwid) {
this.lwid = lwid;
}
public List<Card> getCards() {
return cards;
}
public void setCards(List<Card> cards) {
this.cards = cards;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyDescription() {
return companyDescription;
}
public void setCompanyDescription(String companyDescription) {
this.companyDescription = companyDescription;
}
public String getCompanyWebSite() {
return companyWebSite;
}
public void setCompanyWebSite(String companyWebSite) {
this.companyWebSite = companyWebSite;
}
Now i'm trying to map the object with gson library.
Wallet walletDetails=gson.fromJson(rispostaGetWalletDetails.toString(), Wallet.class);
System.out.println("Balance: "+walletDetails.getBal());
Now when i try to call method on the object i have always null and not the real value.
How i can do?
You have a wrong root level.
Probably, you need to need to get one level down
JSONObject yourObject = json.get("WALLET");
Wallet walletDetails = gson.fromJson(yourObject.toString(), Wallet.class);
To have Gson handle the correct field name mapping while deserializing, you have to register a FieldNamingStrategy like this (using Java 8):
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(field -> field.getName().toUpperCase())
.create();
The strategy will convert each Java field name to match those in your JSON.
This will cover almost all your fields except for those upper-camel-cased in the JSON response, such as "LastName", "CompanyName", etc. In order to map those too, your FieldNamingStrategy will have to become a little bit smarter, like:
field -> {
String fname = field.getName();
return "firstName".equals(fname) || "companyName".equals(fname) /*etc...*/ ? capitalize(fname) : fname.toUpperCase();
}
and so on, I think you got the idea.
The capitalize() method you can find in libraries like Apache Commons Lang or write your own, it's just for examplification here.
Your object variable name doesn't match the json attribute name. "EMAIL" in json should have same EMAIL in object. To overcome this, you could mention #JsonProperty before your attribute declaraction.
for eg:
#JsonProperty("EMAIL")
private String email;

Hibernate Automatically load relationships

I have the following Entity classes UserEntity and TicketEntity. A User has many tickets and many tickets can belong to a user. My question is, is there a way to automatically load all the tickets belonging to a pertaining user by using Hibernate or do I have to manually load all the entity relationships from the DB? I think the .load() does this but I'm not quite sure. In my case could I do something like
userEntity.load()
Any help is appreciated, thanks
UserEntity.java
package com.issuetracking.domain;
/**
*/
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Transient
private String confirmpassword;
#Column(name="verified")
private boolean verified;
#Column(name="role_id")
private int role_id;
#OneToMany(fetch = FetchType.LAZY)
private List<TicketEntity> tickets;
//Getters/Setters
public List<TicketEntity> getTickets() {
return tickets;
}
public void setTickets(List<TicketEntity> tickets) {
this.tickets = tickets;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
TicketEntity.java
package com.issuetracking.domain;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="ticket")
public class TicketEntity {
#Id
#Column(name="ticket_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="date_created")
#Temporal( TemporalType.TIMESTAMP )
private Date date_created;
#Column(name="status_id")
private int status_id;
//private TicketStatus status;
#Column(name="urgency_id")
private int urgency_id;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity belongs_to;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity assigned_to;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getStatus_id() {
return status_id;
}
public void setStatus_id(int status_id) {
this.status_id = status_id;
}
public int getUrgency_id() {
return urgency_id;
}
public void setUrgency_id(int urgency_id) {
this.urgency_id = urgency_id;
}
public UserEntity getBelongs_to() {
return belongs_to;
}
public void setBelongs_to(UserEntity belongs_to) {
this.belongs_to = belongs_to;
}
public UserEntity getAssigned_to() {
return assigned_to;
}
public void setAssigned_to(UserEntity assigned_to) {
this.assigned_to = assigned_to;
}
}
A User has many tickets and many tickets can belong to a user.
In this case relationship should be ManyToMany
My question is, is there a way to automatically load all the tickets belonging to a pertaining user
Use EAGER FetchType instead of LAZY , Like
#OneToMany(fetch = FetchType.EAGER)
private List<TicketEntity> tickets;

Issue with initbinder in spring 3

I have created one model class
#Entity
#Table(name = "tblcoustomer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "tblcoustomer_cid_gen")
#SequenceGenerator(name = "tblcoustomer_cid_gen", sequenceName = "tblcoustomer_cid_seq")
#Column(name = "cid")
private int id;
#ManyToOne(targetEntity = FinancialMonth.class, fetch = FetchType.EAGER)
#JoinColumn(name = "monthId", nullable = false)
private FinancialMonth monthId;
#ManyToOne(targetEntity = Company.class, fetch = FetchType.EAGER)
#JoinColumn(name = "companyId", nullable = false)
private Company companyId;
#ManyToOne(targetEntity = CustomerType.class, fetch = FetchType.EAGER)
#JoinColumn(name = "customerType", nullable = false)
private CustomerType customerType;
private String firstName;
private String lastName;
private String gender;
private int age;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public FinancialMonth getMonthId() {
return monthId;
}
public void setMonthId(FinancialMonth monthId) {
this.monthId = monthId;
}
public Company getCompanyId() {
return companyId;
}
public void setCompanyId(Company companyId) {
this.companyId = companyId;
}
public CustomerType getCustomerType() {
return customerType;
}
public void setCustomerType(CustomerType customerType) {
this.customerType = customerType;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
now when I am trying to load this object using #ModelAttribute I am getting error
#RequestMapping(value = "/saveCustomer")
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("custome") Customer customer) {
Map<String, Object> model = new HashMap<String, Object>();
return new ModelAndView("addCustomer", model);
}
I konw I have to override #initBinder but how do I bind can any one please help me I am getting this error
I can not answer your question without knowing the exception, but there is an typo in your code that may cause an problem:
you have:
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("custome") Customer customer)
But I think it should be model attribute "customer" with an "r" at the end.
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("customer") Customer customer)

Categories