How to show alias column in spring data jpa using native query? - java

I want to show it in my response distance field, but I am not able to do it please help.
Here is my repo class in alias name (distance) I need to attach this distance column with my list of user results.
Repository
String countDistanceQuery = "(3959 * ACOS(COS(RADIANS(:latitude)) * COS(RADIANS(latitude)) * COS(RADIANS(longitude) - RADIANS(:longitude)) + SIN(RADIANS(:latitude)) * SIN(RADIANS(latitude))))";
#Query(value = "SELECT a.* , " + countDistanceQuery + " AS distance FROM user a WHERE a.address LIKE %:address% HAVING distance < 25 ORDER BY distance LIMIT 0, 20" , nativeQuery = true)
public List<User> getNearsetLoactionOfSitter(String address, String latitude, String longitude);
Model
Here I will take the distance attribute as a #Transient to know the JPA does not present in the database.
package com.misha.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import lombok.ToString;
import javax.persistence.*;
#Entity
#ToString
#Table(name = "user",uniqueConstraints = {
#UniqueConstraint(columnNames = "email")
})
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String contactname;
#Column(unique=true)
private String email;
private String password;
private String company;
private String location;
private String address;
private String latitude;
private String longitude;
private String open;
private String close;
private float chargesperhour;
private String logo;
private boolean enabled;
#Transient
private double distance;
#Column(name = "reset_password_token")
private String resetPasswordToken;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {
super();
}
public User(Integer id, String contactname, String email, String password, String company, String location, String address,
String latitude, String longitude, String open, String close, float chargesperhour, String logo,
boolean enabled, String resetPasswordToken) {
super();
this.id = id;
this.contactname = contactname;
this.email = email;
this.password = password;
this.company = company;
this.location = location;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
this.open = open;
this.close = close;
this.chargesperhour = chargesperhour;
this.logo = logo;
this.enabled = enabled;
this.resetPasswordToken = resetPasswordToken;
}
public User(Integer id, String contactname, String email, String password, String company, String location,
String address, String latitude, String longitude, String open, String close, float chargesperhour,
String logo, boolean enabled, double distance, String resetPasswordToken, Set<Role> roles) {
super();
this.id = id;
this.contactname = contactname;
this.email = email;
this.password = password;
this.company = company;
this.location = location;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
this.open = open;
this.close = close;
this.chargesperhour = chargesperhour;
this.logo = logo;
this.enabled = enabled;
this.distance = distance;
this.resetPasswordToken = resetPasswordToken;
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContactname() {
return contactname;
}
public void setContactname(String contactname) {
this.contactname = contactname;
}
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 getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getOpen() {
return open;
}
public void setOpen(String open) {
this.open = open;
}
public String getClose() {
return close;
}
public void setClose(String close) {
this.close = close;
}
public float getChargesperhour() {
return chargesperhour;
}
public void setChargesperhour(float chargesperhour) {
this.chargesperhour = chargesperhour;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getResetPasswordToken() {
return resetPasswordToken;
}
public void setResetPasswordToken(String resetPasswordToken) {
this.resetPasswordToken = resetPasswordToken;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Controller
#GetMapping("/users/search")
public ResponseEntity<List<User>> searchNearestLocation(#RequestParam String address, #RequestParam String latitude, #RequestParam String longitude){
if(!address.isEmpty() && !latitude.isEmpty() && !longitude.isEmpty()) {
try {
List<User> list = userService.getNearsetLoactionOfSitter(address, latitude, longitude);
if( list.isEmpty() || list.size() == 0 ) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(list, HttpStatus.OK);
}catch(Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}else {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I need to add Distance column in my response
I need to show calculated distance in response

#Transient annotation is used to mark a field to be transient for the mapping framework, which means the field marked with #Transient is ignored by mapping framework and the field not mapped to any database column.
Therefore try representing the distance property with #Formula annotation, and apply the distance calculation so that we can obtain the calculated value(I can see that you are calculating the distance based upon the image you have shared).
With #Formula, we can call native database functions and stored procedures and basically do anything that does not break the syntax of an SQL select clause for this field.
Reference: [https://www.concretepage.com/hibernate/formula_hibernate_annotation]

Related

NotBlank validation error in float java (spring boot)

I'm trying to develop an API with an order model and one of the requirements in my model is "price" which takes a float instead of a string
this is the model
package com.api.order_control.models;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "TB_ORDER")
public class OrderModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(nullable = false, length = 11)
private String customerName;
#Column(nullable = false, length = 15)
private String phoneNumber;
#Column(nullable = false, length = 25)
private String address;
#Column(nullable = false, length = 10)
private String doorNumber;
#Column(nullable = true, length = 5)
private String block;
#Column(nullable = false, length = 30)
private String order;
#Column(nullable = false)
private Float price;
#Column(nullable = false)
private LocalDateTime registrationDate;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public LocalDateTime getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDateTime registrationDate) {
this.registrationDate = registrationDate;
}
}
this is the dto package
package com.api.order_control.dtos;
import jakarta.validation.constraints.NotBlank;
public class OrderDto {
#NotBlank
private String customerName;
#NotBlank
private String phoneNumber;
#NotBlank
private String address;
#NotBlank
private String doorNumber;
#NotBlank
private String block;
#NotBlank
private String order;
#NotBlank
private Float price;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String doorNumber() {
return doorNumber;
}
public void doorNumber(String doorName) {
this.doorNumber = doorName;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
}
I created my post method in my controller, but when I test it in my postman I get this error in the terminal:
jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.NotBlank' validating type 'java.lang.Float'. Check configuration for 'price'
I understand that the problem is in float, but I can't understand what's wrong with this code.
update: controller
package com.api.order_control.controllers;
import com.api.order_control.dtos.OrderDto;
import com.api.order_control.models.OrderModel;
import com.api.order_control.services.OrderService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/order")
public class OrderController {
final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
#PostMapping
public ResponseEntity<Object> saveOrder(#RequestBody #Valid OrderDto orderDto) {
var orderModel = new OrderModel();
BeanUtils.copyProperties(orderDto, orderModel);
orderModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(orderService.save(orderModel));
}
}
You need to use #NotNull for Float. The documentation for #NotBlank states:
The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.
So, as long as you don't use #NotBlank on a String or Char it won't work.
If you need additional validations on the value of the float, you can use #Min, #Max, #Positive and more.

I am not able to search my users by email using JPA spring boot

Controller
package com.bird.bird.Controllers;
import com.bird.bird.Entity.Manager;
import com.bird.bird.Repository.ManagerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/manager")
public class ManagerController {
#Autowired
private ManagerRepository managerRepository;
#GetMapping("/teste")
public Object teste() {
return "teste";
}
#PostMapping("/save")
public Manager save(#RequestBody Manager manager){
return managerRepository.save(manager);
};
#GetMapping("/list")
public Iterable<Manager> findAll(){
return managerRepository.findAll();
};
#GetMapping("/findID/{id}")
public Manager findById( #PathVariable int id){
return managerRepository.findById(id);
};
#GetMapping("/findCPF/{CPF}")
public Manager findByCPF( #PathVariable String CPF){
return managerRepository.findByCPF(CPF);
};
}
Repository
package com.bird.bird.Repository;
import java.util.List;
import com.bird.bird.Entity.Manager;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ManagerRepository extends JpaRepository<Manager, Integer> {
Manager findById(int id);
Manager findByEmail(String email);
Manager findByCPF(String CPF);
//Manager findByPhone(String phone);
}
Entity
package com.bird.bird.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "manager")
public class Manager implements java.io.Serializable {
#Id
#GeneratedValue
private int IdManager;
#Column(name = "name", length = 30, nullable = false)
private String Name;
#Column(name = "birth", length = 15, nullable = false)
private String Birth;
#Column(name = "email", length = 30, unique = true, nullable = false)
private String Email;
#Column(name = "CPF", length = 30, unique = true, nullable = false)
private String CPF;
#Column(name = "password", length = 30, nullable = false)
private String Password;
#Column(name = "phone", length = 30, nullable = false)
private String Phone;
#Column(name = "address", length = 30, nullable = false)
private String Address;
#Column(name = "city", length = 30, nullable = false)
private String City;
#Column(name = "state", length = 30, nullable = false)
private String State;
#Column(name = "zipcode", length = 30, nullable = false)
private String ZipCode;
#Column(name = "country", length = 30, nullable = false)
private String Country;
public Manager() {
}
public Manager(String name, String birth, String email, String CPF, String password, String phone, String address, String city, String state, String zipCode, String country) {
this.Name = name;
this.Birth = birth;
this.Email = email;
this.CPF = CPF;
this.Password = password;
this.Phone = phone;
this.Address = address;
this.City = city;
this.State = state;
this.ZipCode = zipCode;
this.Country = country;
}
public int getIdManager() {
return IdManager;
}
public void setIdManager(int idManager) {
IdManager = idManager;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBirth() {
return Birth;
}
public void setBirth(String birth) {
Birth = birth;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getCPF() {
return CPF;
}
public void setCPF(String CPF) {
this.CPF = CPF;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getZipCode() {
return ZipCode;
}
public void setZipCode(String zipCode) {
ZipCode = zipCode;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
Error:
eption: Error creating bean with name 'managerController': Unsatisfied dependency expressed through field 'managerRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'managerRepository' defined in com.bird.bird.Repository.ManagerRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed
Resume:
I would like to do an email search to test, then another login to compare email and password
For your manager class, you have defined all the fields starting with Capital letter ( which is wrong by convention) , therefore you need to update them with small letters only then we will be able to use jpa interface data derived queries ( findByFieldName)
So update the Email field in Manager class to this :
private String email ;
// standard getters and setters
In addition to this,
#GetMapping("/findByEmail/{email}")
public Manager findByEmail(#PathVariable String email){
return managerRepository.findByEmail(email);
};
you need to update this to get mapping. When retrieving objects from database, we use #GetMapping and not Post . also ,we pass variables in the url and not in the request body.
Add #Repositroy annotation to ManagerRepository
and change your class, like
public class Manager {
#Id
#GeneratedValue
private int idManager;
#Column(name = "name", length = 30, nullable = false)
private String name;
#Column(name = "birth", length = 15, nullable = false)
private String birth;
#Column(name = "email", length = 30, unique = true, nullable = false)
private String email;
#Column(name = "CPF", length = 30, unique = true, nullable = false)
private String cpf;
#Column(name = "password", length = 30, nullable = false)
private String password;
#Column(name = "phone", length = 30, nullable = false)
private String phone;
#Column(name = "address", length = 30, nullable = false)
private String address;
#Column(name = "city", length = 30, nullable = false)
private String city;
#Column(name = "state", length = 30, nullable = false)
private String state;
#Column(name = "zipcode", length = 30, nullable = false)
private String zipCode;
#Column(name = "country", length = 30, nullable = false)
private String country;
public ManagerDao(int idManager, String name, String birth, String email, String cpf, String password, String phone, String address, String city, String state, String zipCode, String country) {
this.idManager = idManager;
this.name = name;
this.birth = birth;
this.email = email;
this.cpf = cpf;
this.password = password;
this.phone = phone;
this.address = address;
this.city = city;
this.state = state;
this.zipCode = zipCode;
this.country = country;
}
public int getIdManager() {
return idManager;
}
public void setIdManager(int idManager) {
this.idManager = idManager;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Then delete ";" your methods in controller after "}" is not need.
Gurkirat Singh Guliani answered right

#AttributeOverride not working with Hibernate 5

I am using Hibernate version 5.2.6. I had an instance where I had to use #AttributeOverrides annotation to override the name of an embedded column attribute which I previously used with another entity. But it doesn't seem to be working.
I am getting
Hibernate ERROR - Unknown column 'ADDRESS_LINE_1' in 'field list
The following is my code:
Address.java
package com.myApps.data.entities;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
#Column(name="ADDRESS_LINE_1")
private String addressLine1;
#Column(name="ADDRESS_LINE_2")
private String addressLine2;
#Column(name="CITY")
private String city;
#Column(name="STATE")
private String state;
#Column(name="ZIP_CODE")
private String zipCode;
public Address() {
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
User.java
package com.myApps.data.entities;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Formula;
#Entity
#Table(name = "FINANCES_USER")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "BIRTH_DATE")
private Date birthDate;
#Column(name = "EMAIL_ADDRESS")
private String emailAddress;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="addressline1", column=#Column(name="USER_ADDRESS_LINE_1")),
#AttributeOverride(name="addressline2", column=#Column(name="USER_ADDRESS_LINE_2"))
})
private Address address;
#Column(name = "LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name = "LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name = "CREATED_DATE", updatable = false)
private Date createdDate;
#Column(name = "CREATED_BY", updatable = false)
private String createdBy;
#Formula("lower(datediff(curdate(), birth_date)/365)")
private int age;
public int getAge() {
return age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void setAge(int age) {
this.age = age;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = 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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
Application.java
package com.myApps.data;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.myApps.data.entities.Address;
import com.myApps.data.entities.Bank;
import com.myApps.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
Transaction transaction = session.beginTransaction();
User user = new User();
Address address = new Address();
user.setFirstName("Beth");
user.setLastName("Crimson");
user.setCreatedBy("Mr Crimson");
user.setCreatedDate(new Date());
address.setAddressLine1("22nd street Meadows");
address.setAddressLine2("House no: 15");
user.setAddress(address);
session.save(user);
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
}
finally {
session.close();
}
}
}
I am getting
Hibernate ERROR - Unknown column 'ADDRESS_LINE_1' in 'field list'
I am not able to find any problem with my code.
Please help me resolve this.
If you use camelcase in #Embeddable:
#Column(name="ADDRESS_LINE_1")
private String addressLine1;
#Column(name="ADDRESS_LINE_2")
private String addressLine2;
Then you should use it in overrides as well:
#Embedded
#AttributeOverrides({
#AttributeOverride(name="addressLine1", column=#Column(name="USER_ADDRESS_LINE_1")),
#AttributeOverride(name="addressLine2", column=#Column(name="USER_ADDRESS_LINE_2"))
})
private Address address;

Spring Jpa - hibernate saves a row of nulls in database

a simple save in spring boot jpa / hibernate saves a row of nulls in the database.
package rest.api.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.sql.Blob;
import java.sql.Date;
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private #JsonIgnore Long id;
#Column(name="created")
private Date created;
#Column(name="latitude")
private #JsonIgnore
Float latitude;
#Column(name="longitude")
private #JsonIgnore Float longitude;
#Column(name="password")
private #JsonIgnore String password;
#Column(name="user_name")
private #JsonIgnore String username;
#Column(name="pic_thumbnail")
private #JsonIgnore Blob picThumbnail;
#Column(name="first_name")
private #JsonIgnore String firstName;
#Column(name="middle_name")
private #JsonIgnore String middleName;
#Column(name="last_name")
private #JsonIgnore String lastName;
#Column(name="location_of_residence")
private #JsonIgnore String locationOfResidence;
#Column(name="telephone")
private #JsonIgnore String telephone;
#Column(name="email")
private #JsonIgnore String email;
#Column(name="description")
private #JsonIgnore String description;
#Column(name="date_of_birth")
private #JsonIgnore
java.sql.Date dob = null;
protected User () {}
public User(Long id, Date created, Float latitude, Float longitude, String password, String username, Blob picThumbnail, String firstName, String middleName, String lastName, String locationOfResidence, String telephone, String email, String description, Date dob) {
this.id = id;
this.created = created;
this.latitude = latitude;
this.longitude = longitude;
this.password = password;
this.username = username;
this.picThumbnail = picThumbnail;
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.locationOfResidence = locationOfResidence;
this.telephone = telephone;
this.email = email;
this.description = description;
this.dob = dob;
}
// constructor for Logindetails
public User(Long id, String username, String password, String email) {
this.id = id;
this.created = null;
this.latitude = null;
this.longitude = null;
this.password = password;
this.username = username;
this.picThumbnail = null;
this.firstName = null;
this.middleName = null;
this.lastName = null;
this.locationOfResidence = null;
this.telephone = null;
this.email = email;
this.description = null;
this.dob = null;
}
public User(String username, String email, String password) {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Float getLatitude() {
return latitude;
}
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLongitude() {
return longitude;
}
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Blob getPicThumbnail() {
return picThumbnail;
}
public void setPicThumbnail(Blob picThumbnail) {
this.picThumbnail = picThumbnail;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLocationOfResidence() {
return locationOfResidence;
}
public void setLocationOfResidence(String locationOfResidence) {
this.locationOfResidence = locationOfResidence;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
#Repository
public interface UserRepository extends PagingAndSortingRepository {
}
package rest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import rest.api.data.repository.UserRepository;
import rest.api.entity.User;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
#RestController
#Service
#Transactional
public class UserController {
private final UserRepository userDao;
#Autowired
public UserController(UserRepository userDao) {
this.userDao = userDao;
}
#Transactional
#RequestMapping(value = "/users/{user-id}", method = RequestMethod.GET)
public ResponseEntity<Resource<User>> getSpecificModel(#PathVariable(value = "user-id") Long userId) {
User specificUser = userDao.findOne(userId);
Resource<User> resource = new Resource<>(specificUser, linkTo(methodOn(MessageController.class)
.getSpecificModel(userId)).withSelfRel());
return ResponseEntity.ok(resource);
}
#Transactional
#RequestMapping(value = "/users/{user-id}", method = RequestMethod.DELETE)
public long remove(#PathVariable(value = "user-id") long userId) {
userDao.delete(userId);
return userId;
}
#RequestMapping(value = "/users", method = RequestMethod.POST)
public void registerLoginDetails(#RequestParam(name="username") String username,
#RequestParam(name="email") String email,
#RequestParam(name="password") String password) {
User loginDetails = new User(username, email, password);
userDao.save(loginDetails);
}
#Transactional
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public void registerPersonalDetails() {
}
}
Every column in my users table can take a null, and so it is allowed to save a record in this state. I checked this by executing the equivalent query against the databse manually.
Does anyone have any ideas?
One glaring error is that the constructor in User used to register a user doesn't assign the username, email, password parameters passed in.

Data not persisting in join column using spring-data

The hibernate output is as follows.
Hibernate: insert into usernew (ACTIVE, EMAIL, FIRST_NAME, CGUID, LAST_NAME, MIDDLE_NAME, PIN) values (?, ?, ?, ?, ?, ?, ?)
Hibernate:insert into usernew (ACTIVE, EMAIL, FIRST_NAME, CGUID, LAST_NAME,MIDDLE_NAME, PIN) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into eventnew (ACTIVE, ADDRESS, DESCRIPTION, END_TS, HOST_PHONE_NUMBER,IMAGE, LATITUDE, LONGITUDE, NAME, PLACE_ID, START_TS) values (?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?)
User user = new User();
user.setActive(true);
user.setFirstName("test");
user.setLastName("test");
user.setPin("3333");
user.setEmail("n#f.com");
userRepositoryNew.save(user);
User user1 = new User();
user1.setActive(true);
user1.setFirstName("test");
user1.setLastName("test");
user1.setPin("3333");
user1.setEmail("nauman#f1.com");
userRepositoryNew.save(user1);
Event event = new Event();
event.setName("event");
event.setDescription("testing event");
event.setHostPhoneNumber("4455-33-990");
event.setLongitude("dddd");
EventUser eventUser = new EventUser();
eventUser.setUser(user);
eventUser.setEvent(event);
EventUser eventUser1 = new EventUser();
eventUser.setUser(user1);
eventUser.setEvent(event);
event.getEventUsers().add(eventUser);
event.getEventUsers().add(eventUser1);
eventRepositoryNew.save(event);
Below is the code, not sure why join table is not getting populated.
package com.hive.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.hive.json.marshaller.DateUTCDeserializer;
import com.hive.json.marshaller.DateUTCSerializer;
import com.hive.json.marshaller.ImageDeserializer;
import com.hive.json.marshaller.ImageSerializer;
#Entity
#Table(name = "eventnew")
public class Event implements java.io.Serializable {
private Integer id;
private String name;
private String description;
private String address;
private String latitude;
private String longitude;
#JsonSerialize(using = ImageSerializer.class)
#JsonDeserialize(using = ImageDeserializer.class)
private byte[] image;
private String placeId;
#JsonSerialize(using = DateUTCSerializer.class)
#JsonDeserialize(using = DateUTCDeserializer.class)
private Date startAt;
#JsonSerialize(using = DateUTCSerializer.class)
#JsonDeserialize(using = DateUTCDeserializer.class)
private Date endAt;
private boolean active;
private String hostPhoneNumber;
private Set<User> participants = new HashSet<User>(0);
private Set<EventUser> eventUsers = new HashSet<EventUser>(0);
public Event() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "NAME", nullable = false, length = 10)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "LATITUDE")
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
#Column(name = "LONGITUDE")
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
#Column(name = "START_TS")
public Date getStartAt() {
return startAt;
}
public void setStartAt(Date startAt) {
this.startAt = startAt;
}
#Column(name = "END_TS")
public Date getEndAt() {
return endAt;
}
public void setEndAt(Date endAt) {
this.endAt = endAt;
}
#Column(name = "IMAGE")
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Column(name = "PLACE_ID")
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
#Column(name = "ACTIVE")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "HOST_PHONE_NUMBER")
public String getHostPhoneNumber() {
return hostPhoneNumber;
}
public void setHostPhoneNumber(String hostPhoneNumber) {
this.hostPhoneNumber = hostPhoneNumber;
}
#Transient
public Set<User> getParticipants() {
return participants;
}
public void setParticipants(Set<User> participants) {
this.participants = participants;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.event")
public Set<EventUser> getEventUsers() {
return this.eventUsers;
}
public void setEventUsers(Set<EventUser> eventUsers) {
this.eventUsers = eventUsers;
}
}
package com.hive.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "usernew")
public class User implements java.io.Serializable {
private String guid;
private String firstName;
private String middleName;
private String lastName;
private Integer phoneNumber;
private String email;
private String pin;
private boolean active;
private Set<EventUser> eventUsers = new HashSet<EventUser>(0);
public User() {
}
#Column(name = "CGUID")
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PHONE_NUMBER", unique = true, nullable = false)
public Integer getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "MIDDLE_NAME")
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "PIN")
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
#Column(name = "ACTIVE")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user", cascade = CascadeType.ALL)
public Set<EventUser> getEventUsers() {
return this.eventUsers;
}
public void setEventUsers(Set<EventUser> eventUsers) {
this.eventUsers = eventUsers;
}
}
package com.hive.domain;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name = "eventusernew", catalog = "hive")
#AssociationOverrides({ #AssociationOverride(name = "pk.user", joinColumns = #JoinColumn(name = "USER_ID") ),
#AssociationOverride(name = "pk.event", joinColumns = #JoinColumn(name = "EVENT_ID") ) })
public class EventUser implements java.io.Serializable {
private EventUserId pk = new EventUserId();
// private String state;
// private String comment;
// private String displayName;
public EventUser() {
}
// #Column(name = "STATE")
// public String getState() {
// return state;
// }
//
// #Column(name = "DISPLAY_NAME")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// #Column(name = "COMMENT")
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
#EmbeddedId
public EventUserId getPk() {
return pk;
}
public void setPk(EventUserId pk) {
this.pk = pk;
}
#Transient
public User getUser() {
return getPk().getUser();
}
public void setUser(User stock) {
getPk().setUser(stock);
}
#Transient
public Event getEvent() {
return getPk().getEvent();
}
public void setEvent(Event category) {
getPk().setEvent(category);
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
EventUser that = (EventUser) o;
if (getPk() != null ? !getPk().equals(that.getPk()) : that.getPk() != null)
return false;
return true;
}
public int hashCode() {
return (getPk() != null ? getPk().hashCode() : 0);
}
}
package com.hive.domain;
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
#Embeddable
public class EventUserId implements java.io.Serializable {
private User user;
private Event event;
#ManyToOne
public User getUser() {
return user;
}
public void setUser(User stock) {
this.user = stock;
}
#ManyToOne
public Event getEvent() {
return event;
}
public void setEvent(Event category) {
this.event = category;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EventUserId that = (EventUserId) o;
if (user != null ? !user.equals(that.user) : that.user != null) return false;
if (event != null ? !event.equals(that.event) : that.event != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (user != null ? user.hashCode() : 0);
result = 31 * result + (event != null ? event.hashCode() : 0);
return result;
}
}
you need to cascade your save.
In your Event entity, change the one-to-many to something like this :
#OneToMany(mappedBy="pk.event", cascade=CascadeType.ALL)

Categories