Expected ',' instead of 't' in Postman - java

I am a beginner when it comes to API's and JSON serialization. I'm encountering a weird output. It seems that my JSON output is being wrongly formatted? I am using spring boot 1.59 and when I check my result in postman I am getting the following error:
controller
/**
*
* #return
*/
#PostMapping(value = "/getUser")
#ResponseBody
public User getUSer(#RequestParam int userID) {
System.out.println("Request Id is---->"+userID);
User user = userRepository.findById(userID);
return user;
}
User
#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
//#GeneratedValue(strategy = GenerationType.IDENTITY)
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#NotNull
#Size(max = 65)
#Column(name = "first_name")
private String firstName;
#Size(max = 65)
#Column(name = "last_name")
private String lastName;
#NotNull
#Email
#Size(max = 100)
#Column(unique = true)
private String email;
#NotNull
#Size(max = 128)
private String password;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private UserProfile userProfile;
// Hibernate requires a no-arg constructor
public User() {
}
public User(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
// Getters and Setters (Omitted for brevity)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 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 UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
}
UserProfile
#Entity
#Table(name = "user_profiles")
public class UserProfile implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "phone_number")
#Size(max = 15)
private String phoneNumber;
#Enumerated(EnumType.STRING)
#Column(length = 10)
private Gender gender;
#Temporal(TemporalType.DATE)
#Column(name = "dob")
private Date dateOfBirth;
#Size(max = 100)
private String address1;
#Size(max = 100)
private String address2;
#Size(max = 100)
private String street;
#Size(max = 100)
private String city;
#Size(max = 100)
private String state;
#Size(max = 100)
private String country;
#Column(name = "zip_code")
#Size(max = 32)
private String zipCode;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
private User user;
public UserProfile() {
}
public UserProfile(String phoneNumber, Gender gender, Date dateOfBirth,
String address1, String address2, String street, String city,
String state, String country, String zipCode) {
this.phoneNumber = phoneNumber;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.address1 = address1;
this.address2 = address2;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.zipCode = zipCode;
}
// Getters and Setters (Omitted for brevity)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
UserRepository
public interface UserRepository extends JpaRepository<User, Long> {
User findById(int id);
}
As well as a big long stack trace of fasterxml.jackson errors:
[jackson-databind-2.6.6.jar:2.6.6]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:693) ~[jackson-databind-2.6.6.jar:2.6.6]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:675) ~[jackson-databind-2.6.6.jar:2.6.6]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157) ~[jackson-databind-2.6.6.jar:2.6.6]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149) ~[jackson-databind-2.6.6.jar:2.6.6]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:111) ~[jackson-databind-2.6.6.jar:2.6.6]
at

It happened due to infinite recursion between two entities and I solved using JsonManagedReference, JsonBackReference

Related

How to check if one user have already column with same value

I have a two tables: User and Wallet
User have: id
Wallet have: userId, walletName
Now, I want to avoid that so user cant have two wallets with same name.
I create something but it applies to all users, so if user with id 1 create a wallet with name walletSaving no-one can create wallet with that name, while I want to avoid that, I want to create something to check whether the user with id 1 have already wallet with that name.
So far I have this:
if (walletRepository.existsByWalletName(walletRequest.getWalletName())) {
return ResponseEntity.badRequest().body(new MessageResponse("You already have wallet with that name, choose another!"));
}
After some help I tried with something like this:
#PostMapping("/user/{user_id}/wallets")
public ResponseEntity<?> createWallet(#PathVariable(value = "user_id") Long user_id,
#RequestBody Wallet walletRequest, User user) {
if (walletRepository.existsByUserIdAndWalletName(user.getId(), walletRequest.getWalletName())) {
return ResponseEntity.badRequest()
.body(new MessageResponse("You already have wallet with that name, choose another!"));
}
Its still creating wallets with same name.
Just to provide more info.
User entity
#Entity
#Table(name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
#UniqueConstraint(columnNames = "email")
})
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
#Size(min = 3, max = 20)
private String username;
#NotEmpty
#Size(max = 50)
#Email
private String email;
#NotEmpty
#Size(min = 6)
private String password;
#NotEmpty(message = "Please, insert a first name")
private String firstName;
#NotEmpty(message = "Please, insert a last name")
private String lastName;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String username, String email, String password, String firstName, String lastName) {
this.username = username;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
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 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 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 Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Wallet entity
#Entity
#Table(name = "wallet")
public class Wallet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty(message = "Please, insert a wallet name")
private String walletName;
private double initialBalance;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private User user;
public Wallet() {
}
public Wallet(String walletName, double initialBalance) {
this.walletName = walletName;
this.initialBalance = initialBalance;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getWalletName() {
return walletName;
}
public void setWalletName(String walletName) {
this.walletName = walletName;
}
public double getInitialBalance() {
return initialBalance;
}
public void setInitialBalance(double initialBalance) {
this.initialBalance = initialBalance;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Wallet Repository
boolean existsByUserIdAndWalletName(Long userId, String walletName);
You need to include the userId in your query:
final long userId = getUserId(); // get the currently authenticated user's id
if (walletRepository.existsByUserIdAndWalletName(userId, walletRequest.getWalletName())) {
return ResponseEntity.badRequest()
.body(new MessageResponse("You already have wallet with that name, choose another!"));
}
existsByUserIdAndWalletName(userId, walletName);
or
findByUserIdAndWalletName(userId, walletName);
If id of the user and walletName is provided, it will check only for that user if it has that wallet name or not, and if in that situation returns something (true or result>0), that will mean that for that specific user the wallet name is already taken.
https://www.baeldung.com/spring-data-derived-queries#multiple-condition-expressions

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

When I save an Entity with hibernate the foreign key is not saved always an null

I have two classes User.java and Vehicle.java with OneToMany relationship. When I post via postman a user with 2 vehicles, the data is stored correctly in the DB but the foreign key in the Vehicles table is stored always as null.
User.java
#Entity
#Table(name = "users", schema = "vehicleproject")
public class User {
#Id
#Column(name = "user_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "address")
private String address;
#Column(name = "afm")
private int afm;
#Column(name = "role_id")
private UserType type;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Vehicle> vehicles = new ArrayList<>();
public User(){}
public User(long id, String email, String password, String firstName, String lastName, String address, int afm, UserType type, List<Vehicle> vehicles) {
this.id = id;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = vehicles;
}
public User(long id, String email, String password, String firstName, String lastName, String address, int afm, UserType type) {
this.id = id;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = new ArrayList<>();
}
public User(String email, String password, String firstName, String lastName, String address, int afm, UserType type, List<Vehicle> vehicles) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = vehicles;
}
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAfm() {
return afm;
}
public void setAfm(int afm) {
this.afm = afm;
}
public UserType getType() {
return type;
}
public void setType(UserType type) {
this.type = type;
}
public void addVehicleToList(Vehicle vehicle){
this.vehicles.add(vehicle);
}
public void removeVehicleFromUserList(Vehicle vehicle){
this.vehicles.remove(vehicle);
}
}
Vehicle.java
#Entity
#Table(name = "vehicles", schema = "vehicleproject")
public class Vehicle {
#Id
#Column(name = "vehicle_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "brand")
private String brand;
#Column(name = "model")
private String model;
#Column(name = "creation_date")
private LocalDate creationDate;
#Column(name = "color")
private String color;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
#Column(name = "plate_number")
private String plateNumber;
public Vehicle(){
}
public Vehicle(long id, String brand, String model, LocalDate creationDate, String color, User user, String plateNumber) {
this.id = id;
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.user = user;
this.plateNumber = plateNumber;
}
public Vehicle(String brand, String model, LocalDate creationDate, String color, User user, String plateNumber) {
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.user = user;
this.plateNumber = plateNumber;
}
public Vehicle(long id, String brand, String model, LocalDate creationDate, String color, String plateNumber) {
this.id = id;
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.plateNumber = plateNumber;
}
public String getPlateNumber() {
return plateNumber;
}
public void setPlateNumber(String plateNumber) {
this.plateNumber = plateNumber;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public LocalDate getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDate creationDate) {
this.creationDate = creationDate;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
#JsonIgnore
public User getUser() {
return user;
}
#JsonProperty
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vehicle vehicle = (Vehicle) o;
return id == vehicle.id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
My json payload is:
{
"email": "new#player7.com",
"password": "newplayer2",
"firstName": "ithList",
"lastName": "Constructor",
"address": "Ermou 20",
"afm": 1005733537,
"type": "USER",
"vehicles": [
{
"brand": "MASSERATI",
"model": "GOD",
"creationDate": "2015-05-05",
"color": "WHITE",
"plateNumber": "Amm2421"
},
{
"brand": "Toyota",
"model": "Corolla",
"creationDate": "2015-05-05",
"color": "WHITE",
"plateNumber": "Fmmf2421"
}
]
}
I see this in my spring boot app it inserts all the data for User generating an Id for the new User.
It also inserts all the data for vehicles generating new Ids for Vehicles but in the FK column in Vehicles it inserts null always:
2020-07-12 15:55:20.169 TRACE 14700 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [BIGINT] - [null]
RestController method for inserting a User:
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public User insert(#RequestBody User user) {
return userService.save(user);
}
#KavithakaranKanapathippillai the solution that you proposed is working!
"add this user.getVehicles().forEach(vehicle -> vehicle.setUser(user)); before return userService.save(user);"
But I cannot Understand since it is a Json with vehcles inside the User Object why it is not working directly?
Try to remove #Json from methods getUser and setUser and from field User user, and add to your json the user id:
"user": {"id" = 1}

Prevent something from being joined hibernate

#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "idUser")
public UserEntity getUserEntity() {
return teacher;
}
public void setUserEntity(UserEntity idTeacher) {
this.teacher = idTeacher;
}
The following code is in my data model. I use inheritance and I query this data the following way:
Query query1 = session.createQuery("FROM GroupEntity");
List<GroupEntity> groups = (List<GroupEntity>) query1.list();
The problem is. It will join now all the use information. But I only want to select a couple of things. For example. Only the username. And not the password.
Below the UserEnity:
#Entity
#Table(name = "User", schema = "", catalog = "")
#Inheritance(strategy = InheritanceType.JOINED)
public class UserEntity implements Serializable{
private int idUser;
private GroupEntity groupEntity;
private String email;
private String firstName;
private String lastName;
//ToDo Make this password secure!
private String password;
private boolean admin;
private boolean teacher;
public UserEntity(String email, String firstName, String lastName, String password, boolean admin, boolean teacher) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.admin = admin;
this.teacher = teacher;
}
public UserEntity() {
}
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idUser")
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
#Basic
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Basic
#Column(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Basic
#Column(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Basic
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Basic
#Column(name = "admin")
public boolean getAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
#Basic
#Column(name = "teacher")
public boolean getTeacher() {
return teacher;
}
public void setTeacher(boolean teacher) {
this.teacher = teacher;
}
}

OneToOne ids generated error

i have this error nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): app.Spring.domain.UserDetails.
I now have this user table and in profile i want to edit this UserDetails.
i was trying with GeneratedValue but this doing random id that not associate with user_id also checked generator but this method also dont work.There is so many options so i am lost now.Can someone show some method to mapp this two entities?
User
#Entity
#Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "user_id")
private Long user_id;
#NotBlank
#Size(min = 5, max = 20)
private String username;
#NotBlank
#Size(min = 8, max = 20)
private String password;
private String email;
private String name;
private String surname;
#OneToOne(cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private UserDetails userDetail;
public User() {
}
public User(Long user_id, String username, String email, String name,
String surname, UserDetails userDetail, String password) {
super();
this.user_id = user_id;
this.username = username;
this.email = email;
this.name = name;
this.surname = surname;
this.userDetail = userDetail;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getUser_id() {
return user_id;
}
public final void setUser_id(Long user_id) {
this.user_id = user_id;
}
public void setId(Long user_id) {
this.user_id = user_id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
User_Details
#Entity
#Table(name = "user_address")
public class UserDetails {
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
#Column(name = "user_id")
private Long id;
private String adres1;
private String adres2;
private String city;
private String postcode;
#OneToOne
#PrimaryKeyJoinColumn
private User user;
public UserDetails(Long id, String adres1, String adres2, String city,
String postcode, User user) {
super();
this.id = id;
this.adres1 = adres1;
this.adres2 = adres2;
this.city = city;
this.postcode = postcode;
this.user = user;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAdres1() {
return adres1;
}
public void setAdres1(String adres1) {
this.adres1 = adres1;
}
public String getAdres2() {
return adres2;
}
public void setAdres2(String adres2) {
this.adres2 = adres2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
LOGIC
#RequestMapping(value = "/userDetails", method = RequestMethod.GET)
public String showForm(Model model,
#RequestParam(value = "id", defaultValue = "-1") Long id,
HttpSession session) {
app.Spring.domain.UserDetails va = (id > 0) ? reg.getAdress(id)
: new UserDetails();
model.addAttribute("detal", va);
return "userDetails";
}
#RequestMapping(value = "/userDetails", method = RequestMethod.POST)
public String submit(Model model, #ModelAttribute("detal") UserDetails va,
BindingResult result) {
validator.validate(va, result);
if (result.hasErrors()) {
return "userDetails";
}
reg.saveOrUpdateUserDetails(va);
return "profile";
}
I don't know how to do this with annotations but you might try to manually assign the (hopefully then already present) id fetched from user in the UserDetails entity in the #PrePresist annotated method.
User
#Entity
#Table(name = "USERS")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "user_id")
private Long user_id;
#NotBlank
#Size(min = 5, max = 20)
private String username;
#NotBlank
#Size(min = 8, max = 20)
private String password;
private String email;
private String name;
private String surname;
#OneToOne(mappedBy = "user")
private UserDetails userDetail;
User_detail
#Entity
#Table(name = "user_address")
public class UserDetails {
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
private Long id;
private String adres1;
private String adres2;
private String city;
private String postcode;
#OneToOne
#JoinColumn(name = "user_id")
private User user;

Categories