How to don't serialize the class field in FastJson? - serialization

Today I'm using FastJson(https://github.com/alibaba/fastjson), the following is my demo code.
class User {
private final String name;
private final int age;
private final String birthday;
private String password;
public User(String name, int age, String birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public void setPassword(String pwd) {
this.password = pwd;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getBirthday() {
return birthday;
}
public String getPassword() {
return password;
}
#Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birthday='" + birthday + '\'' +
", password='" + password + '\'' +
'}';
}
}
It will serialize the field which has getXXX method. I do not want to serialize the password, and I will call the getPassword() to get the password value.
I do not want to rename the method getPassword and update the variable password to public.
Does anyone know how to ignore a field when serializing this class?

#JSONField(serialze=false)
public String getPassword() {
return password;
}

Related

Not getting expected record from database when comparing dates in spring boot

I am passing date and email through post request and accepting them in validatebasicdetails api.
When I am comparing the recieved date that is in yyyy-MM-dd format to the one which is stored in database, I am unable to fetch the expected record.
Post request:
{
"emailAddress":"smith#abc.com",
"dateOfBirth":"2019-12-12"
}
When I am printing the object I received from post request it's printing it as
Customer [uniqueIdNumber=null, dateOfBirth=Wed Dec 12 05:30:00 IST 1990, emailAddress=smith#abc.com, firstName=null, lastName=null, idType=null, customeraddress=null, simdetails=null]
the date here is not in yyyy-MM-dd format.
Customerdto.java
package com.jpa.Proj.DTOs;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import com.jpa.Proj.Entities.Customeraddress;
import com.jpa.Proj.Entities.Simdetails;
public class CustomerDTO {
String uniqueIdNumber;
#DateTimeFormat(pattern="yyyy-MM-dd")
Date dateOfBirth;
String emailAddress;
String firstName;
String lastName;
String idType;
Customeraddress customeraddress;
Simdetails simdetails;
public String getUniqueIdNumber() {
return uniqueIdNumber;
}
public CustomerDTO(String uniqueIdNumber, Date dateOfBirth, String emailAddress, String firstName, String lastName,
String idType, Customeraddress customeraddress, Simdetails simdetails) {
super();
this.uniqueIdNumber = uniqueIdNumber;
this.dateOfBirth = dateOfBirth;
this.emailAddress = emailAddress;
this.firstName = firstName;
this.lastName = lastName;
this.idType = idType;
this.customeraddress = customeraddress;
this.simdetails = simdetails;
}
#Override
public String toString() {
return "Customer [uniqueIdNumber=" + uniqueIdNumber + ", dateOfBirth=" + dateOfBirth + ", emailAddress="
+ emailAddress + ", firstName=" + firstName + ", lastName=" + lastName + ", idType=" + idType
+ ", customeraddress=" + customeraddress + ", simdetails=" + simdetails + "]";
}
public CustomerDTO() {
super();
}
public void setUniqueIdNumber(String uniqueIdNumber) {
this.uniqueIdNumber = uniqueIdNumber;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
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 getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public Customeraddress getCustomeraddress() {
return customeraddress;
}
public void setCustomeraddress(Customeraddress customeraddress) {
this.customeraddress = customeraddress;
}
public Simdetails getSimdetails() {
return simdetails;
}
public void setSimdetails(Simdetails simdetails) {
this.simdetails = simdetails;
}
}
Customer.java
package com.jpa.Proj.Entities;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
public class Customer {
#Id
String uniqueIdNumber;
#DateTimeFormat(pattern="yyyy-MM-dd")
Date dateOfBirth;
String emailAddress;
String firstName;
String lastName;
String idType;
#OneToOne(cascade= CascadeType.ALL)
#JoinColumn(name="addressId")
Customeraddress customeraddress;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "simId")
Simdetails simdetails;
public String getUniqueIdNumber() {
return uniqueIdNumber;
}
public Customer(String uniqueIdNumber, Date dateOfBirth, String emailAddress, String firstName, String lastName,
String idType, Customeraddress customeraddress, Simdetails simdetails) {
super();
this.uniqueIdNumber = uniqueIdNumber;
this.dateOfBirth = dateOfBirth;
this.emailAddress = emailAddress;
this.firstName = firstName;
this.lastName = lastName;
this.idType = idType;
this.customeraddress = customeraddress;
this.simdetails = simdetails;
}
#Override
public String toString() {
return "Customer [uniqueIdNumber=" + uniqueIdNumber + ", dateOfBirth=" + dateOfBirth + ", emailAddress="
+ emailAddress + ", firstName=" + firstName + ", lastName=" + lastName + ", idType=" + idType
+ ", customeraddress=" + customeraddress + ", simdetails=" + simdetails + "]";
}
public Customer() {
super();
}
public void setUniqueIdNumber(String uniqueIdNumber) {
this.uniqueIdNumber = uniqueIdNumber;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
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 getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public Customeraddress getCustomeraddress() {
return customeraddress;
}
public void setCustomeraddress(Customeraddress customeraddress) {
this.customeraddress = customeraddress;
}
public Simdetails getSimdetails() {
return simdetails;
}
public void setSimdetails(Simdetails simdetails) {
this.simdetails = simdetails;
}
}
CustomerRepo.java
package com.jpa.Proj.Repos;
import java.util.Date;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import com.jpa.Proj.DTOs.CustomerDTO;
import com.jpa.Proj.Entities.Customer;
import com.jpa.Proj.Entities.Simdetails;
import com.jpa.Proj.Entities.Simoffers;
#Service
public interface CustomerRepo extends JpaRepository<Customer,Integer>{
#Query("SELECT c from Customer c WHERE c.emailAddress=:cemail AND c.dateOfBirth =:cdob")
Customer findByEmailAdressAndDob(#Param("cemail") String firstName,#Param("cdob") Date lastName);
#Query("Select c from Customer c Where c.uniqueIdNumber=:cun")
Customer findByID(#Param("cun") String un);
}
Following is my api:
public class Validatebasicdetailsapi {
#Autowired
CustomerRepo crepo;
#PostMapping
public CustomerDTO validatebasicdetails(#RequestBody CustomerDTO cdto) {
System.out.println(cdto);
Customer cdt= crepo.findByEmailAdressAndDob(cdto.getEmailAddress(),cdto.getDateOfBirth());
System.out.println("Customer="+cdt);
// System.out.println("date recieved="+cdto.getDateOfBirth());
return new CustomerDTO();
}
}

SQL syntax Error on Java Jersey GET CRUD operation

I'm trying to retrieve the information of the faculty with the students attending it and the subjects corresponding to the student.
Here is the SQL error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM faculty f
inner join student_faculty sf on sf.student_id=s.user_id'
Here is the picture in line 116 the s.user_id is not on yellow color indicating something not right:
Here is it how I want it to look like:
{
"fid": "1",
"name": "Mathematcis",
"enrolled_students": [
{
"id": "student1",
"username": "user",
"full_name": "userstudent",
"subjects": [
{
"id": 1,
"name": "Programim 1"
},
{
"id": 2,
"name": "Programim 2"
},
{
"id": 3,
"name": "Calculus"
},
{
"id": 4,
"name": "Discrete mathematics"
}
]
}
]
Here is how postman shows it:
Here is my code:
public Faculty getFacultyStudent(int id) throws Exception {
Connection connection = null;
Faculty faculty = new Faculty();
Student student = new Student();
student.setSubjectList(new ArrayList<>());
faculty.setStudentList(new ArrayList<>());
try {
connection = new MysqlDbConnectionService().getConnection();
String select = "SELECT f.fid,\n" +
" f.fname,\n" +
" f.university_id,\n" +
" s.user_id,\n" +
" s.username,\n" +
" s.password,\n" +
" s.fullname,\n" +
" s.email,\n" +
" subj.id,\n" +
" subj.name,\n" +
"FROM faculty f\n" +
" inner join student_faculty sf on sf.student_id=s.user_id\n" +
" INNER JOIN student s ON sf.student_id=s.user_id\n" +
" INNER JOIN faculty_subject fs on f.fid = fs.faculty_id\n" +
" inner join subject subj on fs.subject_id = subj.id\n" +
"WHERE fid = ?;";
PreparedStatement ps = connection.prepareStatement(select);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if(faculty.getFid()==0) {
faculty.setFid(rs.getInt("fid"));
faculty.setFname(rs.getString("fname"));
}
student.setId(rs.getString("user_id"));
student.setUsername(rs.getString("username"));
student.setPassword(rs.getString("password"));
student.setFullName(rs.getString("fullname"));
student.setEmail(rs.getString("email"));
Subject subject=new Subject();
subject.setId(rs.getInt("id"));
subject.setName(rs.getString("name"));
student.getSubjectList().add(subject);
faculty.getStudentList().add(student);
}
} catch (Exception e) {
System.out.println(e + "Retrieve not successful");
}
return faculty;
}
Faculty Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
import java.util.Collections;
import java.util.List;
public class Faculty {
#SerializedName("id")
private int fid;
#SerializedName("university_id")
private int university_id;
#SerializedName("name")
private String fname;
#SerializedName("Enrolled Students:")
private List<String> studentList;
public Faculty() {
this.fid = fid;
this.university_id=university_id;
}
public void setFid(int fid)
{
this.fid = fid;
}
public int getFid()
{
return fid;
}
public void setUniversityid(int university_id)
{
this.university_id=university_id;
}
public int getUniversityid()
{
return university_id;
}
public void setFname(String fname)
{
this.fname = fname;
}
public String getFname()
{
return fname;
}
public void setStudentList(List<String> studentList) {
this.studentList = studentList;
}
public List<Object> getStudentList()
{
return Collections.singletonList(studentList);
}
}
Student Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Student {
#SerializedName("id")
private String id;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("fullname")
private String fullName;
#SerializedName("email")
private String email;
#SerializedName("subjects")
private List<Subject> subjectList;
public Student() {
}
public Student(String id, String username, String password, String fullName, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.fullName = fullName;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Subject> getSubjectList() {
return subjectList;
}
public void setSubjectList(List<Subject> subjectList) {
this.subjectList = subjectList;
}
}
Subject Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Subject {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
public Subject() {
this.id = id;
this.name=name;
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
Here is my ER Diagram:
I was reading through the code and the error and it appears to be just your sentence.
"subj.name , \n" + "FROM faculty f\n" +
That comma after the column name and before the FROM clause is causing that error.
Try to remove it and test it again

Spring RestController ignoring #jsonProperty/JsonGetter/JsonSetter

I am using Springboot 2.1.2.RELEASE. I have a get request with an object as input parameter. Expecting the attributes in my class to be request parameters. My EmployeeBean has properties in java naming convention. But I need the custom names to request parameters. Tried to achieve that using #JsonProperty/ #Jsongetter/ #JsonSetter annotations but its not working. Am I missing something?
#RequestMapping(value="/api", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
public List<Map<String, Object>> getEmployeeData(EmployeeBean employeeBean
#Data
public class EmployeeBean implements Serializable {
private static final long serialVersionUID = -2757478480787308113L;
#JsonProperty(value="first_name")
private String firstName;
#JsonProperty(value="last_name")
private String lastName;
Try this,
private String firstName;
private String lastName;
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;
}
#JsonProperty(value="first_name")
public void setFirst_name(String firstName) {
this.firstName = firstName;
}
#JsonProperty(value="last_name")
public void setLast_name(String lastName) {
this.lastName = lastName;
}
controller
#RestController
public class JsonController {
#RequestMapping(value="/api", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
public List<Map<String, Object>> getEmployeeData(EmployeeBean employeeBean) {
System.out.println("employeeBean: "+employeeBean);
return null;
}
}
result:
employeeBean: EmployeeBean [firstName=firstName10, lastName=lastName20]
I've tested and it's worked
other options, using JsonCreator in constructor:
private String firstName;
private String lastName;
#JsonCreator
public EmployeeBean(#JsonProperty("first_name") String first_name, #JsonProperty("last_name") String last_name) {
this.firstName = first_name;
this.lastName = last_name;
}
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;
}

JDBC/SQL - ID is always 0

so i'm trying to insert an hardcoded member to my Members table. I'm using Spring Boot & JDBC on Eclipse.
This is my schema.sql:
CREATE TABLE Members
(
ID int not null,
LastName varchar(255) not null,
FirstName varchar(255) not null,
PhoneNumber integer not null,
created timestamp not null,
primary key(ID)
);
INSERT INTO MEMBERS (ID, LASTNAME, FIRSTNAME,PHONENUMBER, CREATED)
VALUES(1001, 'Max', 'Mad', 0547547547, sysdate());
i got a findAll method in a DAO class:
public List<Member> findAll(){
return jtemp.query("select * from members", new BeanPropertyRowMapper<Member>(Member.class));
}
when i run it, it returns:
[Member [id=0, firstName=Mad, lastName=Max, phoneNumber=547547547, created=2017-10-31 18:57:21.606]]
As you can see the ID wasn't inserted for some reason.
my Member class is like this:
public class Member {
private long id;
private String firstName;
private String lastName;
private long phoneNumber;
private Date created;
public Member(long id, String firstName, String lastName, long phoneNumber, Date created) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.created = created;
}
public long getUserId() {
return id;
}
public void setUserId(long userId) {
this.id = userId;
}
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 long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#Override
public String toString() {
return "Member [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", phoneNumber="
+ phoneNumber + ", created=" + created + "]";
}
}
How can i fix it?
I tried to inserted different numbers, but i always get a zero in the log.
Thanks
Column names of the query must match the setters in the target object.
Your query has a column named id but there is no setId method. You should either rename setUserId to setId or in the query give the alias user_id to id column.
From BeanPropertyRowMapper documentation:
Column values are mapped based on matching the column name as obtained from result set metadata to public setters for the corresponding properties. The names are matched either directly or by transforming a name separating the parts with underscores to the same name using "camel" case.

Cannot get Java #StoredProcedure to work, could not prepare statement

Hi,
I having problem with #StoredProcedureQuery just getting the error "could not prepare statement"? I am not sure why storedprocedure will not run , just keep getting this error:
"Caused by: org.h2.jdbc.JdbcSQLException: Function "SP_ARCHIVE_OLD_BOOKS" not found; SQL statement: call sp_archive_old_books(?,?) [90022-193]"
Named parameters are used for a callable statement, but database metadata indicates named parameters are not supported
#Entity
#Cacheable(value = true)
#Table(name = "Book")
#NamedStoredProcedureQuery(name = "archiveOldBooks", procedureName = "sp_archive_books",
parameters = {
#StoredProcedureParameter(name = "archiveDate", mode = ParameterMode.IN, type = Date.class),
#StoredProcedureParameter(name = "warehouse", mode = ParameterMode.IN, type = String.class),
#StoredProcedureParameter(name = "maxBookArchived", mode = ParameterMode.INOUT, type = Integer.class)
})
#NamedQuery(name = FIND_ALL_BOOKS, query = "select b from Book b")
#SequenceGenerator(name = "SEQ_BOOK", initialValue = 50)
public class Book {
public static final String FIND_ALL_BOOKS = "book.findAllBooks";
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_BOOK")
private int id;
#NotNull
#Min(1)
private Integer quantity;
#NotNull
#AllItemTypes
#Enumerated(EnumType.STRING)
private ItemType itemType;
#NotNull
#Title
private String title;
#NotNull
#Price
private Float price;
#NotNull
#Description
private String description;
#NotNull
#Isbn
private String isbnNumber;
#NotNull
#InitDate
private Date initDate;
#NotNull(message = "Invalid illustration is set to null")
private Boolean illustrations;
#NotNull
#PageNumber
private Integer numberOfPages;
#NotNull
#Version
#Min(1)
private Integer version;
#NotNull
#Author
private String author;
#NotNull
#Min(1519)
private Integer year;
// ======================================
// = Constructors =
// ======================================
public Book(){
}
public Book(Integer quantity, ItemType itemType, String title, Float price, String description, String isbnNumber, Date initDate, Boolean illustrations, Integer numberOfPages, Integer version, String author, Integer year) {
this.quantity = quantity;
this.itemType = itemType;
this.title = title;
this.price = price;
this.description = description;
this.isbnNumber = isbnNumber;
this.initDate = initDate;
this.illustrations = illustrations;
this.numberOfPages = numberOfPages;
this.version = version;
this.author = author;
this.year = year;
}
public static String getFindAllBooks() {
return FIND_ALL_BOOKS;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIsbnNumber() {
return isbnNumber;
}
public void setIsbnNumber(String isbnNumber) {
this.isbnNumber = isbnNumber;
}
public Date getInitDate() {
return initDate;
}
public void setInitDate(Date initDate) {
this.initDate = initDate;
}
public Boolean getIllustrations() {
return illustrations;
}
public void setIllustrations(Boolean illustrations) {
this.illustrations = illustrations;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(Integer numberOfPages) {
this.numberOfPages = numberOfPages;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", quantity=" + quantity +
", itemType=" + itemType +
", title='" + title + '\'' +
", price=" + price +
", description='" + description + '\'' +
", isbnNumber='" + isbnNumber + '\'' +
", initDate=" + initDate +
", illustrations=" + illustrations +
", numberOfPages=" + numberOfPages +
", version=" + version +
", author='" + author + '\'' +
", year=" + year +
'}';
}
}
public abstract class AbstractPeristEntityClass {
protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
protected EntityManager em;
protected EntityTransaction tx;
#Before
public void initEntityManager() throws Exception {
em = emf.createEntityManager();
tx = em.getTransaction();
}
#After
public void closeEntityManager() throws SQLException {
if (em != null) em.close();
}
protected Long getRandomId() {
return Math.abs(new Random().nextLong());
}
}
public interface Constants {
String PERSISTENCE_UNIT_NAME = "TEST";
}
public class Book_v2_IT extends AbstractPeristEntityClass {
#Test
public void shouldCallANamedStoredProcedureQuery() throws Exception {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("archiveOldBooks");
// Set the parameters and execute
query.setParameter("archiveDate", new Date());
query.setParameter("maxBookArchived", 1000);
query.execute();
}
#Test
public void shouldCallAStoredProcedureQuery() throws Exception {
StoredProcedureQuery query = em.createStoredProcedureQuery("sp_archive_old_books");
query.registerStoredProcedureParameter("archiveDate", Date.class, ParameterMode.IN);
query.registerStoredProcedureParameter("maxBookArchived", Integer.class, ParameterMode.IN);
// Set the parameters and execute
query.setParameter("archiveDate", new Date());
query.setParameter("maxBookArchived", 1000);
query.execute();
}
}