Struts2 + Json Serialization of items - java

I have the following classes:
public class Student {
private Long id ;
private String firstName;
private String lastName;
private Set<Enrollment> enroll = new HashSet<Enrollment>();
//Setters and getters
}
public class Enrollment {
private Student student;
private Course course;
Long enrollId;
//Setters and Getters
}
I have Struts2 controller and I would like to to return Serialized instance of Class Student only.
#ParentPackage("json-default")
public class JsonAction extends ActionSupport{
private Student student;
#Autowired
DbService dbService;
public String populate(){
return "populate";
}
#Action(value="/getJson", results = {
#Result(name="success", type="json")})
public String test(){
student = dbService.getSudent(new Long(1));
return "success";
}
#JSON(name="student")
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
It returns me the serializable student object with all sub classes, but I would like to have only student object without the hashset returned .
How can I tell Struts to serialize only the object?
I do have Lazy loading enabled and hashset is returned as proxy class.

See the answer here which shows the use of include and exclude properties. I don't think the example clearly shows excluding nested objects however I have used it for this purpose. If you still have issues I'll post a regex which will demonstrate this.
Problem with Json plugin in Struts 2
Edit:
Here is an example of using exclude properties in an annotation which blocks the serialization of a nested member:
#ParentPackage("json-default")
#Result(type = "json", params = {
"excludeProperties",
"^inventoryHistory\\[\\d+\\]\\.intrnmst, selectedTransactionNames, transactionNames"
})
public class InventoryHistoryAction extends ActionSupport {
...
inventoryHistory is of type InventoryHistory a JPA entity object, intrnmst references another table but because of lazy loading if it were serialized it would cause an Exception when the action is JSON serialized for this reason the exclude parameter has been added to prevent this.
Note that
\\
is required for each \ character, so a single \ would only be used in the xml where two are required because of escaping for the string to be parsed right.

#Controller
#Results({
#Result(name="json",type="json"
, params={"root","outDataMap","excludeNullProperties","true"
,"excludeProperties","^ret\\[\\d+\\]\\.city\\.province,^ret\\[\\d+\\]\\.enterprise\\.userinfos","enableGZIP","true"
})
})
public class UserinfoAction extends BaseAction {
#Action(value="login")
public String login(){
if(jsonQueryParam!=null && jsonQueryParam.length()>0)
{
user = JsonMapper.fromJson(jsonQueryParam, TUserinfo.class);
}
Assert.notNull(user);
//RESULT="ret" addOutJsonData: put List<TUserinfo> into outDataMap with key RESULT for struts2 JSONResult
addOutJsonData(RESULT, service.login(user));
return JSON;
}
public class TUserinfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String userid;
private String username;
private String userpwd;
private TEnterpriseinfo enterprise;
private String telphone;
private TCity city;
......
}
public class TEnterpriseinfo implements java.io.Serializable {
private String enterpriseid;
private String enterprisename;
private Set<TUserinfo> userinfos = new HashSet<TUserinfo>(0);
.......}
before set the excludeProperties property,the result is below:
{"ret":[
{
"city":{"cityename":"tianjin","cityid":"12","cityname":"天津"
,"province": {"provinceename":"tianjing","provinceid":"02","provincename":"天津"}
}
,"createddate":"2014-01-07T11:13:58"
,"enterprise":{"createddate":"2014-01-07T08:38:00","enterpriseid":"402880a5436a227501436a2277140000","enterprisename":"测试企业2","enterprisestate":0
,"userinfos":[null,{"city":{"cityename":"beijing","cityid":"11","cityname":"北京","province":{"provinceename":"beijing","provinceid":"01","provincename":"北京市"}
},"comments":"ceshi","createddate":"2004-05-07T21:23:44","enterprise":null,"lastlogindate":"2014-01-08T08:50:34","logincount":11,"telphone":"2","userid":"402880a5436a215101436a2156e10000","username":"0.5833032879881197","userpwd":"12","userstate":1,"usertype":0}]
}
,"lastlogindate":"2014-01-08T10:32:43","logincount":0,"telphone":"2","userid":"402880a5436ab13701436ab1b74a0000","username":"testUser","userpwd":"333","userstate":1,"usertype":0}]
}
after set the excludeProperties property,there are not exist province and userinfos nodes, the result is below:
{"ret":
[{
"city":{"cityename":"tianjin","cityid":"12","cityname":"天津"}
,"createddate":"2014-01-07T11:13:58"
,"enterprise":{"createddate":"2014-01-07T08:38:00","enterpriseid":"402880a5436a227501436a2277140000","enterprisename":"测试企业2","enterprisestate":0}
,"lastlogindate":"2014-01-08T11:05:32","logincount":0,"telphone":"2","userid":"402880a5436ab13701436ab1b74a0000","username":"testUser","userpwd":"333","userstate":1,"usertype":0
}]
}

Related

How to reference a list of objects like that is not a DynamoDB table

I have a table with a string attribute that is my hask key and another attribute that is of type list, but when doing some operation whose query goes through this list an error is returned that the list object must have the #DynamoDBTable annotation but the object is not a table.
Error: "com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: class com.beasu.appbeasu.adapter.db.entity.ParesEntity not annotated with #DynamoDBTable
Look:
#DynamoDBTable(tableName = "tb_01_pare")
#ToString
#EqualsAndHashCode
public class DataPareEntity {
private String codDist;
private List<PareEntity> pares;
#DynamoDBHashKey(attributeName = "cod_dist")
public String getCodDist() {
return codDist;
}
public void setCodDist(String codDist) {
this.codDist= codDist;
}
#DynamoDBAttribute(attributeName= "obt_lis_pares")
public List<ParesEntity> getPares() {
return pares;
}
public void setPares(List<PareceresEntity> pareceres) {
this.pareceres = pareceres;
}
}
#AllArgsConstructor
#NoArgsConstructor
#DynamoDBDocument
public class ParesEntity {
private String codDist;
private String numFun;
private String txtJus;
private String indDec;
private String dateHr;
} // getters and setters...
If anyone knows the reason for this problem and can let me know I would be very grateful.

How to set and get value from the composite key

I am trying to set the value cid in student class using SubjectMark->private String cid;
How to set and get value in my controller.
Entity's and controller method below:
#Entity
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SubjectMark id;
private String fullName;
private Integer totalMarks;
private Double percentage;
private String grade;
//Setters and getters
}
//Composit class
#Embeddable
public class SubjectMark implements Serializable {
//Composit key
private String cid;
//Setters and getters
}
In my controller I try to set value like this:
#RequestMapping(value="getstdata",method=RequestMethod.GET)
#ResponseBody
public String getstdata(#RequestParam(value="cid")String cid){
//Some code
try{
Student st=new Student();
st.getId().setCid(cid);//Set value like this but it is getting null pointer exception
//some code
//retuen some value
}
Please help me!
1st part of question:
I am trying to set the value cid in student class using SubjectMark->private String cid; How to set and get value in my controller.
#Entity
#Table
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SubjectMark subjectMarkId;
private String otherField;
// setters, getters
}
//Composite class
#Embeddable
public class SubjectMark implements Serializable {
private String cId;
// setter, getter
}
//Controller
#GetMapping(value = "getstdata")
public String getStData(#RequestParam(value="cid") String cid) {
Student student = new Student();
student.setSubjectMark(new SubjectMark());
student.getSubjectMark().setCId(cid);//cid value dynamic
// some other code
return "";
}
2nd part of question:
Now, one of the reason null exception happens when you try to call a method(either setter or getter) from a null object.
you need to write a get set method in your class I guess...
try writing something like
private String cid;
public String Cid { get => cid; set => cid = value; }

How to exclude object property

I using Orika mapper to map two beans. i would like to exclude billingSummary.billableItems property while mapping. I am trying below option but it is not working.
Any help?
public class Cart {
private String id;
private String name;
private BillingSummary billingSummary;
private String address;
//with getter and setter methods
}
public class BillingSummary {
private String billingItem;
private String billingItemId;
private BillableItems billableItems;
...
// with getter setter methods
}
//FilteredCart is same as Cart.
public class FilteredCart {
private String id;
private String name;
private BillingSummary billingSummary;
private String address;
//with getter and setter methods
}
#Component
public class CartMapper extends ConfigurableMapper {
#Override
public void configure(MapperFactory mapperFactory) {
mapperFactory.classMap(Cart.class,FilteredCart.class).exclude("billingSummary.billableItems").byDefault().register();
}
}
What you can do is adding another mapping to the mapperFactory in order to define how you want to map the BillingSummary to itself. In this way, when mapping from Cart to FilteredCart, you can configure to exclude to map the billableItems.
Therefore, your CartMapper will look like this:
#Component
public class CartMapper extends ConfigurableMapper {
#Override
public void configure(MapperFactory mapperFactory) {
mapperFactory.classMap(BillingSummary.class, BillingSummary.class).exclude("billableItems").byDefault().register();
mapperFactory.classMap(Cart.class,FilteredCart.class).byDefault().register();
}
}

How to get subclasses attributes using SingleTableInheritance with SpringMVC

i am working on a web application using Spring, Hibernate and SpringMVC,
i am facing a problem with retreiving values from a subclass table using SingleTable inheritance strategy, here are my entities
Client.java (Super class)
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "typeClient", discriminatorType = DiscriminatorType.STRING)
public class Client implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idClient;
private String matricule;
private String statut;
private String secteurDactivite;
private String nomClient;
private String emailClient;
private String numTelephone;
private String adresse;
//constructor
//getter & setters
}
Societe.java (subClass1)
#Entity
#DiscriminatorValue("Societe")
public class Societe extends Client implements Serializable{
private String nomResponsable;
private String emailResponsable;
private String telResponsable;
private String nomSuperieur;
private String emailSuperieur;
private String telSuperieur;
private String commentaire;
//constructeur sans parametre
public Societe() {
}
}
Particulier.java (subclass2)
#Entity
#DiscriminatorValue("Particulier")
public class Particulier extends Client implements Serializable {
private String cin;
//constructeur sans parametres
public Particulier() {
}
}
in my implementation i am using this methode to get a particular client with his ID
ClientDaoImpl.java
public class ClientDaoImpl implements ClientDao {
#PersistenceContext
private EntityManager em;
#Override
public Client getClientByID(int id_client) {
return em.find(Client.class, id_client);
}
When i ran this code i only selected the attributes of the superClass Client.
what i am trying to do is to get a client with its subclass whether it's a Societe or Particulier based on its type or clientID.
Please Help
As you don't know the type of client before querying and only it's ID, you will need to inspect the type and cast after you retrieve the record;
Client client1 = clientDao.getClientById(clientID);
if (client1 instanceof Societe) {
((Societe) client1).getCommentaire();
}
Depending on your use case, it may be useful to map the result of the client query to a ClientDescriptor object which contains all the fields for all client types and returns either nulls or blanks. This means you don't have to keep checking for client type everywhere;
public class ClientDTO {
//client fields
private String nomResponsable = "";
....
//subclass 1 fields.... initialize to empty
//subclass 2 fields .... initialize to empty
public ClientDTO (Client client) {
// set fields for client entity
}
public ClientDTO (Societe societe) {
this (societe);
// set societe fields.
}
// other constructors.
}
You can modify your getClientByID method to accept an additional argument which will say what type of entity your want to retrieve and get back:
public class ClientDaoImpl implements ClientDao {
#PersistenceContext
private EntityManager em;
public <T extends Client> T getByID(int id_client, Class<T> klass) {
return em.find(klass, id_client);
}
}
And you can use this dao in the following manner:
Societe societe = clientDao.getByID(42, Societe.class);
Particulier particulier = clientDao.getByID(43, Particulier.class);

Entity with Inner class for building the entity

I am trying out one-to-one mapping in JPA,
here i have taken relationship between Student and Contact, each student has an contact.
i have create Student entity as follows,
#Entity
#Table(name="TBL_STUDENT")
public class Student implements Serializable{
public Student(){ }
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private Integer studentId;
#OneToOne(targetEntity=StudentContact.class,fetch=FetchType.LAZY)
#JoinColumn(name="CONTACT_ID")
private StudentContact contact;
....
....
....
}
Now the StudentContact entity as follows,
#Entity
#Table(name="TBL_STD_CONTACT")
public class StudentContact extends Serializable{
public StudentContact(){ }
#Id
#Column(name="ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer contactId;
...
...
// all the properties mapped,
public static class Builder{
private Integer contactId;
private String phoneNo;
private String streetAddr;
....
// all the properties as same as StudentContact
public Builder(String val){
this.city = val;
}
public Builder setContactId(Integer contactId) {
this.contactId = contactId;
return this;
}
// rest all the setter methods are like the above, having return type Builder
public StudentContact build(){
return new StudentContact(this);
}
}
private StudentContact(Builder builder){
this.contactId = builder.contactId;
this.city = builder.city;
this.phoneNo = builder.phoneNo;
.......
...
}
}
In the above StudentContact Entity you can see i have created an inner class Builder, whose responsibility is to build StudentContact object by using its "build" method, which you can see in below mentioned StudentTest class
Now i have written a StudentTest class which has the main method as follows,
public class StudentTest {
public static void main(String [] args){
try{
StudentDAO dao = new StudentDAO();
Student student = dao.getEntity(110);
StudentContact contact = new StudentContact.Builder("Bhubaneshwar")
.setPhoneNo("9867342313")
.setPinCode("400392")
.setState("Odhisha").build();
student.setContact(contact);
dao.updateEntity(student);
}catch(Exception e){
e.printStackTrace();
}
}
When i run StudentTest from netbeans IDE, it gives as error
Exception in thread "main" java.lang.VerifyError: Constructor must call super() or this() before return in method com.entities.StudentContact.<init>()V at offset 0
I am not able to understand this error, whether this error is because for the inner class which i have created in StudentContact class,
How can i solve this,
java.lang.VerifyError means that the bytecode is not correct. Usually it can be fixed with a full clean/rebuild of the project. (I sometimes saw it after package/class renaming, or class moving from one package to another).
As mentionned in comments : extends Serializable is not correct. (maybe the cause of your bytecode issue ?)

Categories

Resources