JSON Names from SpringFramework #Controller, #ResponseBody - json

I've got a simple Spring Controller who's purpose is to return a RESTful JSON response of my entity objects. Its returning the data in standard camelCase names which match my entity. However, I'd like the JSON names to match the database fields, which is simply TitleCase. Is there a simple way to do this? Below is a sample of the Controller and the JSON returned.
#Controller
#RequestMapping(path="/Users")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping(path="/List")
public #ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
Resulting JSON:
{"id":1,"userName":"SYSTEM","password":"xxxxx","firstName":"System","lastName":"System","phone":"XXX-XXX-XXXX","email":"system#test.com","reviewer":false,"admin":false}
Here's my User entity class:
package com.prs.business;
import java.io.Serializable;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name="username")
#JsonProperty("UserName")
private String userName;
private String password;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String phone;
private String email;
#Column(name="isreviewer")
private boolean reviewer;
#Column(name="isadmin")
private boolean admin;
#Column(name="isactive")
private boolean active;
#Column(name="datecreated")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
private Timestamp dateCreated;
public User() {
userName = "";
password = "";
}
public User(int id, String userName, String password, String firstName, String lastName, String phoneNumber,
String email, boolean reviewer, boolean admin) {
super();
this.id = id;
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.phone = phoneNumber;
this.email = email;
this.reviewer = reviewer;
this.admin = admin;
}
public User(String un, String pw, String fn, String ln, String pn, String e, boolean m, boolean a) {
setUserName(un);
setPassword(pw);
setFirstName(fn);
setLastName(ln);
setPhoneNumber(pn);
setEmail(e);
setReviewer(m);
setAdmin(a);
}
public int getId() {
return id;
}
public void setId(int 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 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 getPhone() {
return phone;
}
public void setPhoneNumber(String phoneNumber) {
this.phone = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isReviewer() {
return reviewer;
}
public void setReviewer(boolean inReviewer) {
this.reviewer = inReviewer;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean inAdmin) {
this.admin = inAdmin;
}
public boolean isActive() {
return admin;
}
public void setActive(boolean inActive) {
this.admin = inActive;
}
public Timestamp getDateCreated() {
return dateCreated;
}
public void setDateCreated(Timestamp dateCreated) {
this.dateCreated = dateCreated;
}
#Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", firstName=" + firstName
+ ", lastName=" + lastName + ", phoneNumber=" + phone + ", email=" + email + ", reviewer="
+ reviewer + ", admin=" + admin + "]";
}
}

How to enable pascal case for all JSON property names?
Put the following setting in your application.properties
spring.jackson.property-naming-strategy=UPPER_CAMEL_CASE

userRepository.findAll() will probably return a POJO, right?
In that pojo, before the getters or before the fields declaratin, you can add an annotion like
#JsonProperty("<hereYouWriteTheNameYouPrefer>")
private String userName;
or
private String userName;
#JsonProperty("<hereYouWriteTheNameYouPrefer>")
public String getUserName(){
return userName;
}

Related

Creating a role in a role

I made a spring boot user management app and every time I update the user, the role doesn't overwrite.
Like this: roles=[Role{name='Role{name='ROLE_USER'}'}]}
roles=[Role{name='Role{name='Role{name='ROLE_USER'}'}'}]}
What can I change in my code to be just a Role;
User.class :
`
package com.webusermanagement.entity;
import javax.persistence.*;
import java.util.Collection;
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name="enabled")
private Boolean enabled;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Collection<Role> roles;
public User(){}
public User(String username, String password, String firstName, String lastName, boolean enabled, Collection<Role> roles) {
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.enabled = enabled;
this.roles = roles;
}
public User(String username, String password, String firstName, String lastName, boolean enabled) {
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.enabled = enabled;
}
public User(String username, String password, Collection<Role> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long 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 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 boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", enabled=" + enabled +
", roles=" + roles +
'}';
}
}
t`
Role.class:
`
package com.webusermanagement.entity;
import javax.persistence.*;
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
public Role(){}
public Role(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Role{" +
"name='" + name + '\'' +
'}';
}
}
`
UserDAOImplementation.class
`
#Repository
public class UserDAOImplementation implements UserDAO {
#Autowired
private EntityManager entityManager;
#Override
public User findByUserName(String username) {
Session currentSession = entityManager.unwrap(Session.class);
// now retrieve/read from database using username
Query<User> theQuery = currentSession.createQuery("from User where username=:uName");
theQuery.setParameter("uName", username);
User theUser = null;
try {
theUser = theQuery.getSingleResult();
} catch (Exception e) {
theUser = null;
}
return theUser;
}
#Override
public void save(User user) {
Session currentSession = entityManager.unwrap(Session.class);
currentSession.saveOrUpdate(user);
}
#Override
public void deleteByUsername(String username) {
Session session = entityManager.unwrap(Session.class);
Query query=session.createQuery("delete from User where username=:userName");
query.setParameter("userName",username);
query.executeUpdate();
}
#Override
public List<User> findAll() {
Session session = entityManager.unwrap(Session.class);
Query query=session.createQuery("from User");
List<User>users=query.getResultList();
return users;
}
#Override
public void update(User user) {
Session currentSession = entityManager.unwrap(Session.class);
currentSession.update(user);
}
}
`

Spring JDBC Unable to insert

I am new to SpringBoot and I am using SpringBoot with JDBC for making an API. The INSERT is not working properly, I had made ID Unique and AutoIncremeneted it. Before I was inserting the ID and it was causing no problems.I am using MySql as the database.
The JSON I am using in POST is:
{
"name":"Name",
"email":"namegmail.com",
"dob":"2000-04-09",
"age":21
}
I am getting this Error.
{
"timestamp": "2021-06-20T13:10:16.925+00:00",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/octet-stream' not supported",
"path": "/api/v1/NewStudent"
}
Controller
#RestController
#RequestMapping(path = "api/v1/")
public class StudentController {
private StudentService studentService;
#Autowired
public StudentController(StudentService service){
this.studentService=service;
}
#GetMapping("/home")
public String getHome(){
return "Hey Welcome to Home";
}
#PostMapping("/NewStudent")
public void registerNewStudent(#RequestBody StudentClass studentClass){
studentService.addNewStudent(studentClass);
}
#GetMapping("/student/{id}")
public StudentClass getStudentSearch(#PathVariable(value = "id") Long userId){
return studentService.getStudentSelect(userId);
}
#GetMapping("/AllStudents")
public List<StudentClass> getAllStudents(){
return studentService.getAllStudents();
}
}
StudentDao
public class StudentDaoClass implements StudentDao{
#Autowired
private JdbcTemplate jdbctemplate;
private List<StudentClass> selectAll;
#Override
public int insert(StudentClass student) {
String query="INSERT INTO Student(std_name,std_email,std_dob,std_age)" +
"VALUES(?,?,?,?)";
int res=this.jdbctemplate.update(query,student.getName(),student.getEmail(),student.getDob(),student.getId());
return res;
}
#Override
public StudentClass selectStudent(Long id) {
String query="SELECT * FROM Student WHERE std_id=?";
RowMapper<StudentClass> rowMapper=new RowMapperClass();
StudentClass studentClass=this.jdbctemplate.queryForObject(query,rowMapper,id);
return studentClass;
}
#Override
public List<StudentClass> selectAllStudents() {
String query="SELECT * FROM Student";
selectAll=this.jdbctemplate.query(query,new RowMapperClass());
return selectAll;
}
public JdbcTemplate getJdbctemplate() {
return jdbctemplate;
}
public void setJdbctemplate(JdbcTemplate jdbctemplate) {
this.jdbctemplate = jdbctemplate;
}
}
StudentClass
public class StudentClass {
#Id
private Long id;
private String name;
private LocalDate dob;
private Integer age;
private String email;
public StudentClass() {
}
public StudentClass(String name, String email,LocalDate dob ,Integer age) {
this.name = name;
this.dob = dob;
this.age = age;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "StudentClass{" +
"id=" + id +
", name='" + name + '\'' +
", dob=" + dob +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}
I think your rest call is not even reaching the jdbc part as there is problem in your rest request. I believe you are not setting the content-type properly. Try making below changes and see.
When sending the request please set 'Content-Type' header property to 'application/json'
and enhance your below handler method what is consumes.
#PostMapping(path="/NewStudent", consumes="application/json")
public void registerNewStudent(#RequestBody StudentClass studentClass){
studentService.addNewStudent(studentClass);
}
Try debugging your application. Your rest call should reach your above handler method.

What is org.h2.jdbc.JdbcSQLDataException: Invalid value "3" for parameter "columnIndex" [90008-200]?

I'm trying to use JDBC authentication for my spring security when I hit the error message below. I'm trying to register all the email and password in the User class to be valid logins. I'm not sure if there is a problem with my sql statement or my User class. Any help if appreciated!
Caused by: org.h2.jdbc.JdbcSQLDataException:
Invalid value "3" for parameter "columnIndex" [90008-200]
Spring security
#Autowired
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.jdbcAuthentication()
// To find logins in the h2 database
.dataSource(dataSource)
.usersByUsernameQuery("select email, password " +
"from User " +
"where email = ?")
.authoritiesByUsernameQuery("select email, role " +
"from User " +
"where email =?");
}
User class
#Entity
public class User {
private String firstName;
private String lastName;
#Size(min = 6, message ="Enter at least 6 characters")
#ValidPassword
private String password;
private String matchingPassword;
private String passportNumber;
private String address;
private String phoneNumber;
#ValidEmail
private String email;
// Mark as primary key
#Id
// Will be auto generated
#GeneratedValue
private long id;
private String role;
public User(#NotNull String firstName, #NotNull String lastName,
#Size(min = 6, message = "Enter at least 6 characters") #NotNull String password,
#NotNull String passportNumber, #NotNull String address, #NotNull String phoneNumber, String email,
String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passportNumber = passportNumber;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
this.role = role;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + ", password=" + password
+ ", matchingPassword=" + matchingPassword + ", passportNumber=" + passportNumber + ", address="
+ address + ", phoneNumber=" + phoneNumber + ", email=" + email + ", id=" + id + ", role=" + role + "]";
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
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 getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setId(long id) {
this.id = id;
}
protected User() {
}
public long getId() {
return id;
}
}
EDIT: Answer to this question is marked below
Spring security expects 3 columns for the usersByUserName query. Here is the default query used if you don't specify one.
public static final String DEF_USERS_BY_USERNAME_QUERY
= "select username, password, enabled from users where username = ?";
So if you don't have such column for enabling and disabling user, use the following query
select email, password, 'true' as enabled from User where email = ?
Reference
https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.html

ResponseBody get object list from object. #JsonIgnore not working

Ok i have class User
#Entity
#Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id_user;
#Column(nullable = false)
private String email;
#Column(nullable = true)
private String password;
private String firstname;
private String lastname;
private Boolean enabled;
private String phone;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_company")
private Company company;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_rank")
#JsonBackReference
private Authority authorities;
#OneToMany(mappedBy = "create_by")
private List<Cms> create_by;
#OneToMany(mappedBy = "modified_by")
private List<Cms> modified_by;
#OneToMany(mappedBy = "id_issuer")
private List<Ticket> id_issuer;
#OneToMany(mappedBy = "id_responsible")
private List<Ticket> id_responsible;
#OneToMany(mappedBy = "id_author")
private List<IssueMsg> id_author;
public User() {
}
public User(String email, String password, String firstname, String lastname, String phone, Company company, Authority authority) {
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.enabled = true;
this.phone = phone;
this.authorities = authority;
}
#Override
public String toString() {
return "User [id_user=" + id_user + ", email=" + email + ", password="
+ password + ", firstname=" + firstname + ", lastname="
+ lastname + ", enabled=" + enabled + ", phone=" + phone
+ "]";
}
public Long getId_user() {
return id_user;
}
public void setId_user(Long id_user) {
this.id_user = id_user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#JsonIgnore
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 Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
/**
* #return the authorities
*/
public Authority getAuthorities() {
return authorities;
}
/**
* #param authorities the authorities to set
*/
public void setAuthorities(Authority authority) {
this.authorities = authority;
}
#JsonIgnore
public List<Cms> getCreate_by() {
return create_by;
}
public void setCreate_by(List<Cms> create_by) {
this.create_by = create_by;
}
#JsonIgnore
public List<Cms> getModified_by() {
return modified_by;
}
public void setModified_by(List<Cms> modified_by) {
this.modified_by = modified_by;
}
#JsonIgnore
public List<Ticket> getId_issuer() {
return id_issuer;
}
public void setId_issuer(List<Ticket> id_issuer) {
this.id_issuer = id_issuer;
}
#JsonIgnore
public List<Ticket> getId_responsible() {
return id_responsible;
}
public void setId_responsible(List<Ticket> id_responsible) {
this.id_responsible = id_responsible;
}
#JsonIgnore
public List<IssueMsg> getId_author() {
return id_author;
}
public void setId_author(List<IssueMsg> id_author) {
this.id_author = id_author;
}
}
And class Company
#Entity
#Table(name = "companies")
public class Company implements Serializable {
private static final long serialVersionUID = 6255059577246367312L;
#Id
#GeneratedValue
private Long id_company;
private String name;
private String adress;
private String email;
private String phone;
#OneToMany(mappedBy = "company")
#JsonManagedReference
private List<User> user;
#Override
public String toString() {
return "Company [id_company=" + id_company + ", name=" + name
+ ", adress=" + adress + ", email=" + email + ", phone="
+ phone + "]";
}
public Company() {
}
public Company(Long id_company, String name, String adress, String email,
String phone) {
this.id_company = id_company;
this.name = name;
this.adress = adress;
this.email = email;
this.phone = phone;
}
public Long getId_company() {
return id_company;
}
public void setId_company(Long id_company) {
this.id_company = id_company;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
I getting all result from database, and returning this as response body.
My JSON response get user.company.user list and i don't need what. I was try add on getter company user #JsonIgnore but i getting error
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.ArrayList[1]->projektzespolowy.model.User["company"]->projektzespolowy.model.Company_$$_jvstcb8_2["handler"])
I read many post about fix thix but no one help. This is possible to ignore this user list in company?
I think you are getting this exception because User#company is lazy fetched so jackson tries to serialize a hibernate proxy. Try with fetch = FetchType.EAGER on the mapping, or call user.getCompany() in the controller prior to returning the results.

Glassfish 4/MySQL Connection Pooling is not working

I have tried to settup derby and mysql databases, but both times it could not find the table. I have created the table, and I connect to it from different devices on my network. I just cant connect to it using the connection pool.
I receive the following messages "java.sql.SQLSyntaxErrorException: Table/View 'USERS' does not exist" or "Table/View 'ADDRESSES' does not exist" for another example.
I can ping the database, and everything is working using the drivermanager, but it is not working using the connection pool. My pool configuration:
user:user
password:password
url:jdbc:mysql://localhost:3306/thechef
port:3306
DatabaseName:thechef
ServerName:localhost
Here is my file:
Users.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
#ManagedBean
#SessionScoped
public class Users {
private String userName;
private String firstName;
private String lastName;
private String city;
private String zipcode;
private String state;
private String country;
private String email;
#Resource (name="jdbc/thechef")
DataSource ds;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
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 save() throws SQLException
{
if (ds==null)
throw new SQLException ("unable to obtain datasource");
Connection connection = ds.getConnection();
if (connection==null)
throw new SQLException ("unable to obtain datasource");
try{
PreparedStatement addEntry = connection.prepareStatement("INSERT INTO USERS (USERNAME, FIRSTNAME, LASTNAME)VALUES (?,?,?)");
addEntry.setString(1, getUserName());
addEntry.setString(2, getFirstName());
addEntry.setString(3, getLastName());
addEntry.executeUpdate();
return "index";
}
finally{
connection.close();
}
}
}