How to set and get value from the composite key - java

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; }

Related

Read from property file in entity

I have an attribute expiryDate in my entity. i want when i ceate an instance from this entity, i set the value of the attribute expiryDate. The value is in the application.yml file. I used Properties.getProperty in the construct but it didn't work
application.yml:
application:
token:
expiredIn: 1440
Token entity:
public abstract class Token implements Serializable {
#Id
private UUID id;
private int expiryIn;
public Token() {
this.expiryIn= Properties.getProperty("application.token.expiredIn");
}
}
#UPDATE
I used #Value but the value of expiration is always 0
public abstract class Token implements Serializable {
#Id
private String id;
private Date expiryDate;
#Value("${application.token.expiredIn}")
private static int expiration;
public Token() {
this.expiryDate = calculateExpiryDate(expiration);
}
private Date calculateExpiryDate(final int expiryTimeInMinutes) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime());
}
}
Try:
public abstract class Token implements Serializable {
#Id
private UUID id;
#Value("${application.token.expiredIn}")
private int expiryIn;
}
#Value will take the value from application.yml file and inject it into expiryIn.

How to find all data in DB using Hibernate?

I have following classes
#Entity
#Table(name="prm_user_permission")
public class UserPermission {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="prm_permission_id")
private Integer permissionId;
#Column(name="prm_permission_name")
private String permissionName;
#Column(name="prm_short_description")
private String shortDescription;
#Column(name="prm_description")
private String description;
#Column(name="prm_url")
private String permissionUrl;
#Column(name="prm_control")
private String control;
#Column(name="prm_create_user")
private Integer creatUser;
#Column(name="prm_parent_id")
private Integer parentId;
#Column(name="prm_system_id")
private Integer systemId;
// Getter and Setter
And my code is
public List<UserPermission> findAllBySystemId(int systemId) {
List<UserPermission> userPermission = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(eq("UserPermission.systemId", systemId).list();
return userPermission;
}
Now i want to get all data from this (UserPermission) table by "systemId".If i pass systemId=1 then it should give all data where the column is '1'.
what is wrong in my code? while running it shows error like
org.hibernate.QueryException: could not resolve property: UserPermission of:
com.kgfsl.collections.core.security.models.UserPermission
Plz anybody help
What do the criteria() method returns?
And, try with systemId directly (eg: remove the UserPermission.)
Try with Restrictions.eq()
public List<UserPermission> findAllBySystemId(int systemId) {
List<UserPermission> userPermission = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.eq("systemId", systemId)).list();
return userPermission;
}
Assuming that your criteria() method would be,
session.createCriteria(UserPermission.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 ?)

multiple language support data from db

My application has entities with nameEn and nameDe for english and german. But only english being used now. Since there are so many entities available, I wanted to have a generic class which can return the selected language entries,but for multiple entries my approach didn't work.
#Entity
#Table(name="employee")
public class Employee implements java.io.Serializable {
// Fields
private Integer id;
private String nameEn;
private String nameDe;
//Getter, Setter Methods
}
#Entity
#Table(name="address")
public class Address implements
java.io.Serializable {
private String descriptionEn;
private String descriptionDe;
}
public interface ILabelText {
String getNameEn();
String getNameDe();
String getDescriptionEn();
String getDescriptionDe();
}
public abstract class LabelText implements ILabelText, Serializable {
private static final long serialVersionUID = 1L;
protected String descriptionEn;
protected String descriptionDe;
private Logger log = Logger.getLogger(LabelText.class);
String language = FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage();
public String getDescription() {
log.info("Language Selected is " + language);
if (language.equals("De")) {
return getDescriptionDe();
} else {
return getDescriptionEn();
}
}
public String getName() {
log.info("Language Selected is " + language);
if (language.equals("De")) {
return getNameDe();
} else {
return getNameEn();
}
}
}
//In Xhtml, based on selected locale, display value accordingly
<h:outputText value="#{emp.getName()}" />
<h:outputText value="#{add.getDescription()}" />
You can create an entity Lang like this
#Entity
public class Lang implements Serializable
{
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#NotNull
private String key;
#NotNull
private String translation;
}
and use it in your Address like this
#OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
#MapKey(name = "key")
protected Map<String, Lang> name;
Then you are able to access the correct language in JSF:
<h:outputText value="#{emp.name[userLocale].translation}" />
The expression userLocale should be resolved to your language key (en, de, ...) or can be hardcoded e.g. #{emp.name['en'].translation}.
Is more easy you create a table with translations:
e.g:
People -> All of your persons
PersonTranslations
People | id
PersonTranslations | locale; person_id;
then on your Person class you set the language for all attributes on predicate
Person.description (this will search on PersonTranslation using a person_id key, and a locale)
some like that PersonTranslation.find(1, 'en');

Struts2 + Json Serialization of items

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
}]
}

Categories

Resources