Im totally new to springboot and it get these errors when i try debugging them. They include;
could not resolve property: orderID of: com.DigitalVision.service.models.DeliveryStatus
could not resolve property: orderID of: com.DigitalVision.service.models.DeliveryStatus [Select s from com.DigitalVision.service.models.DeliveryStatus s where s.orderID = ?1]
Among a few of them, some included that there was an error creating bean with name deliveryStatusRepository.
Courier controller class
package com.DigitalVision.service.controllers;
import com.DigitalVision.service.models.Courier;
import com.DigitalVision.service.services.CourierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/courier")
#Service
public class CourierController
{
private CourierService courierService;
#Autowired
public CourierController(CourierService courierService) {
this.courierService = courierService;
}
#CrossOrigin
#RequestMapping(path = "/update-status/{status}/order-id/{orderId}",
method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getAttendanceByDateRange(#PathVariable("status") String status,
#PathVariable("orderId") Long orderId) throws Exception {
Courier courier = courierService.updatestatus(status,orderId);
if (courier == null ) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
return new ResponseEntity(courier, HttpStatus.ACCEPTED);
}
}
I have not done a controller class for the delivery status one yet
Courier class
#Entity
#Table
public class Courier implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long CourierID;
public Long OrderID;
public String Status;
Delivery status
#Entity
#Table
public class DeliveryStatus implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long DeliveryStatusID;
public Long OrderID;
public String Status;
public LocalDate Date;
Order class
public class Order implements Serializable {
public Long OrderID;
public Long CustomerID;
public Long ProductID;
public String Quantity;
Deliverystatusrepository
import com.DigitalVision.service.models.DeliveryStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
#Repository
public interface DeliveryStatusRepository extends JpaRepository<DeliveryStatus, Long> {
#Query("Select s from DeliveryStatus s where s.orderID = ?1")
DeliveryStatus findDeliveryStatusIDByOrderID(Long id);
}
Courier service
public Courier updatestatus(String Status, Long courierID){
Courier courier = courierRepository.getReferenceById(courierID);
courier.setStatus(Status);
Courier courierSave = courierRepository.save(courier);
if(courierSave == null ){
return null;
}
deliveryStatusService.updatestatus(courierSave);
return courierSave;
}
Delivery status service
public DeliveryStatus updatestatus (Courier courier ){
DeliveryStatus deliveryStatus = deliveryStatusRepository.findDeliveryStatusIDByOrderID(courier.OrderID);
deliveryStatus.setStatus(courier.Status);
return deliveryStatusRepository.save(deliveryStatus);
}
The purpose of this code is to automatically change the status in the deliverystatus table when the courier status column is updated.
If anyone can help me find the error it would be greatly appreciated
Related
I am trying my hands at Hibernate Relation Mapping(OneToOne, etc) exercises using Spring Boot. Before you ask, I have already consulted this link : [https://stackoverflow.com/questions/11104897/hibernate-attempted-to-assign-id-from-null-one-to-one-property-employee]. I understand that the weak entity needs to have a ref to the parent entity, but I am not able to figure out, why I need to do that explicitly in Person class constructor?
The Codes are as follows.
SpringApplication:
package com.OneToOne.OneToOneMappingPractice;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class App
{
public static void main( String[] args )
{
ApplicationContext applContext = SpringApplication.run(App.class, args);
String[] beanNames = applContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for(String beanName : beanNames)
System.out.println(beanName);
}
}
CRUDController.java:
package com.OneToOne.OneToOneMappingPractice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin
public class CRUDController
{
private static int randomNumber=(int) Math.random();
#Autowired
private CRUDControllerRepository repository;
#GetMapping(value="/add")
public void add()
{
Person person = new Person("Person"+randomNumber, "Street"+randomNumber, randomNumber);
repository.save(person);
randomNumber+=1;
}
#GetMapping(value="/getAll")
public List<Person> getAll()
{
return repository.findAll();
}
#DeleteMapping(value="/deleteAll")
public void deleteAll()
{
repository.deleteAll();
}
}
Person.java:
package com.OneToOne.OneToOneMappingPractice;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
public class Person
{
private String name;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private int Id;
#OneToOne(mappedBy="person", cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Address address;
public Person() {}
public Person(String name, String streetName, int house_number)
{
super();
this.name = name;
this.address=new Address();
this.address.setStreetName(streetName);
this.address.setHouse_number(house_number);
//this.address.setPerson(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java:
package com.OneToOne.OneToOneMappingPractice;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
#Entity
public class Address {
#Id
#Column(name="user_id")
private int Id;
private int house_number;
private String streetName;
#OneToOne
#MapsId
#JoinColumn(name = "user_id")
private Person person;
public Address(){}
public int getHouse_number() {
return house_number;
}
public void setHouse_number(int house_number) {
this.house_number = house_number;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
// public Person getPerson() {
// return person;
// }
public void setPerson(Person person) {
this.person = person;
}
}
CRUDControllerRepository.java:
package com.OneToOne.OneToOneMappingPractice;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public interface CRUDControllerRepository extends JpaRepository<Person, Integer>
{
Person save(Person person);
void deleteAll();
List<Person> findAll();
}
Following are my questions :
As you can see, in the Person class parameterized constructor, I have commented out the line : this.address.setPerson(this);. If I keep this line commented out, I get the exception : "attempted to assign id from null one-to-one property [com.OneToOne.OneToOneMappingPractice.Address.person]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.OneToOne.OneToOneMappingPractice.Address.person]". If I remove the comment syntax, it works perfectly. Why do I need to explicitly do this? Isn't the #OneToOne annotation supposed to take care of these references by itself?
2.If I enable the Person getPerson() method in the Address class, it recursively goes on, until the stack explodes: "Cannot render error page for request [/getAll] and exception [Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException".
Why cant Hibernate itself determine that it needs to stop at that boundary itself, instead of fetching the Parent Object again?
Am I missing something here about these mapping annotations, or anything else?
1- As you can see, in the Person class parameterized constructor, I
have commented out the line : this.address.setPerson(this);. If I keep
this line commented out, I get the exception : "attempted to assign id
from null one-to-one property
Hibernate will not set it explicitly because it does not know to which person this address belongs to you need to specify that explicitly.
The purpose of #OneToOne is to tell hibernate where to get the rest of the data when it is already mapped.
2.If I enable the Person getPerson() method in the Address class, it recursively goes on, until the stack explodes: "Cannot render error
page for request [/getAll] and exception [Could not write JSON:
Infinite recursion (StackOverflowError); nested exception is
com.fasterxml.jackson.databind.JsonMappingException". Why cant
Hibernate itself determine that it needs to stop at that boundary
itself, instead of fetching the Parent Object again?
The exception is caused by Jackson serializer and not from hibernate.
you can look at the examples here to see how it is fixed https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion.
Note: This is a project which has a connection with database on other tables. I just made a new table, but i must have something wrong in my codes, because i cant get what i want.
I have a City table, and this table has 3 columns, named id, name, city_id. And i imported a csv file, so when i query, I can see some data.
I wrote Entity, Repository, Controller, and Service, in Java on Eclipse
What should I do? For example, when i search like localhost:8181/mfc/city/getAllCities that should give me all the cities as json
Could you tell me what i should add?
City.java
package com.mfc.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="city")
public class City{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="city_name")
String cityName;
#Column(name="city_id")
int cityId;
public City() {
super();
}
public City(int id, String cityName, int cityId) {
super();
this.id = id;
this.cityName = cityName;
this.cityId = cityId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
CityController.java
package com.mfc.admin.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mfc.admin.service.CityService;
import com.mfc.entity.City;
#RestController
#RequestMapping("/city")
public class CityController {
private static final Logger logger = LogManager.getLogger(CityController.class);
#Autowired
CityService cityService;
#RequestMapping(value="/getAllCities", method=RequestMethod.GET, headers = "Accept=application/json")
public List getCities() {
logger.trace("CityController: getAllCities begins");
List listOfCities = cityService.getAllCities();
logger.trace("CityController: getAllCities ends");
return listOfCities;
}
#RequestMapping(value="/getCity/{id}", method=RequestMethod.GET, headers = "Accept=application/json")
public City getCityById(#PathVariable int id) {
return cityService.getCity(id);
}
}
CityService.java
package com.mfc.admin.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mfc.entity.City;
import com.mfc.repository.CityRepository;
#Service("cityService")
public class CityService {
#Autowired
CityRepository cityDTO;
#Transactional
public List getAllCities() {
return cityDTO.getAllCities();
}
#Transactional
public City getCity(int id) {
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
}
}
CityRepository.java
package com.mfc.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mfc.entity.City;
public interface CityRepository extends JpaRepository<City, Integer>{
List getAllCities();
City getCity();
}
In the CityService you call the CityRepository like this
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
But no such method is defined in the CityRepository. Try using this line return cityDTO.findById(id).get();
You can't see the method findById(Integer id) in the CityRepository, but it is there, because the CityRepository extends JpaRepository<City, Integer>. Find some Spring Data tutorial to know what's really going on in here, long story short the Spring Data is able to generate a lot of standard methods for you.
The method cityDTO.findById(id) returns Optional<City>, not City. To get the instance of City, just add '.get()' method, as it is in the example. It should work for you if city exists in the database. For proper work with Optional find some tutorial. It is a wrapper of an object that may or may not be present, detailed explanation is out of the scope of this answer.
maybe you can try to set up message converter manualy, google MappingJackson2HttpMessageConverter and you'll know what to do.
Not sure what is happening here. The error is
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' - Unsatisfied dependency expressed through constructor parameter 1"
Am I missing something here?
My controller -
import com.***.model.User;
import com.***.service.AuthTokenService;
import com.***.service.Authentication;
import com.***.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#Controller
#RestController
#RequestMapping("/api/v1")
public class AuthenticationController {
#Autowired
UserService userService;
AuthTokenService authTokenService;
#GetMapping(path = "/users")
public ResponseEntity<?> listUser() {
List<User> resource = userService.getUser();
return ResponseEntity.ok(resource);
}
#PostMapping(path = "/register")
public ResponseEntity<?> register(#RequestBody User newUser) {
User user = userService.findUserByEmail(newUser.getEmail());
User unconfirmedUser = userService.registerUser(newUser);
return ResponseEntity.ok(unconfirmedUser);
}
My UserService -
import com.***.model.User;
import com.***.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
#Component
#AllArgsConstructor
public class UserService {
#Autowired
UserRepository userRepository;
AuthTokenService authTokenService;
EmailSenderService emailSenderService;
void sendAuthenticationEmail(String userMail, String token) {
final SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userMail);
mailMessage.setSubject("Mail Confirmation Link!");
mailMessage.setFrom("<Mail Service>");
mailMessage.setText( "Thank you for joining ***! Please click below to activate your account." + "http://8080/api/v1/confirm?token=" + token);
emailSenderService.sendEmail(mailMessage);
}
public User registerUser(User user) {
final Authentication authenticationToken = new Authentication(user);
authTokenService.saveAuthenticationToken(authenticationToken);
sendAuthenticationEmail(user.getEmail(), authenticationToken.getUserToken());
return userRepository.save(user);
}
public void confirmUser(Authentication authenticationToken) {
final User user = authenticationToken.getUser();
user.setEnabled(true);
userRepository.save(user);
authTokenService.deleteAuthenticationToken((long) authenticationToken.getId());
}
}
Authentication -
import com.***.model.User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.UUID;
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Authentication {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String userToken;
private LocalDate dateTimeCreated;
#OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
#JoinColumn(nullable = false, name = "id")
private User user;
Authentication(User user) {
this.user = user;
this.dateTimeCreated = LocalDate.now();
this.userToken = UUID.randomUUID().toString();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public LocalDate getDateTimeCreated() {
return dateTimeCreated;
}
public void setDateTimeCreated(LocalDate dateTimeCreated) {
this.dateTimeCreated = dateTimeCreated;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Authentication token repo -
package com.***.repository;
import com.***.service.Authentication;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
#Repository
public interface AuthenticationTokenRepository extends CrudRepository<Authentication, Long> {
Optional<Authentication> findAuthenticationToken(String token);
}
Picture of file structure HERE
Log of error
Based on your error it looks like you don't know how to create JpqRepository method signature based queries. You can read about it here : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
I'm guessing that your method in AuthenticationTokenRepository called findAuthenticationToken(String someField) should be named findBySomeField(String someField). Also make sure you have getter for someField
Would be easier if you could provide your AuthenticationTokenRepository and Authenctication classes
Edit:
Change your method in AuthenticationTokenRepository to findByUserToken(String userToken)
I have following problem. This is my entity:
package application.model;
import lombok.Data;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
#NamedQueries({
#NamedQuery(name = User.GET_USERS, query = User.QUERY_GET_USERS),
#NamedQuery(name = User.VERIFY_CREDENTIALS, query = User.QUERY_VERIFY_CREDENTIALS),
#NamedQuery(name = User.GET_USER_ROLE, query = User.QUERY_GET_USER_ROLE),
#NamedQuery(name = User.GET_USER_ID_BY_EMAIL, query = User.QUERY_GET_USER_ID_BY_EMAIL)
})
#Data
#Entity
#Table(name = "users")
public class User {
public static final String GET_USERS = "User.get_users";
public static final String QUERY_GET_USERS = "select u from User u";
public static final String VERIFY_CREDENTIALS = "User.verify_credentials";
public static final String QUERY_VERIFY_CREDENTIALS = "select u from User u where u.email = :email and u.password = :password";
public static final String GET_USER_ROLE = "User.get_role";
public static final String QUERY_GET_USER_ROLE = "select u.roles from User u where u.id= :id";
public static final String GET_USER_ID_BY_EMAIL = "User.get_userId_by_mail";
public static final String QUERY_GET_USER_ID_BY_EMAIL = "select u from User u where u.email= :email";
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "id")
public int id;
#NotEmpty(message="provide firstname")
#Size(min=4,message = "minimum 4 chars")
#Column(name="firstname",nullable = false)
private String firstname;
#NotEmpty(message="provide lastname")
#Size(min=4,message = "minimum 4 chars")
#Column(name="lastname",nullable = false)
private String lastname;
#NotEmpty(message="provide mail")
#Email(message = "mail should be valid")
#Column(name="email",unique = true,nullable = false)
private String email;
#NotEmpty(message="provide pass")
#Size(min=4,message = "minimum 4 chars")
#Column(name="password",nullable = false)
private String password;
#ManyToMany
#JoinTable(name="user_roles")
private List<Role> roles;
}
dao layer:
package application.dao;
import application.model.Role;
import application.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
#Repository
public class UserDAOImpl implements UserDAO {
#PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager em;
#Transactional
#Override
public User addUser(User user) {
return em.merge(user);
}
#Override
public User addCustomerRole(User user) {
List<Role> roles= new ArrayList<>();
roles.add(em.find(Role.class,3));
user.setRoles(roles);
return user;
}
#Override
public User addSellerRole(User user) {
List<Role> roles= new ArrayList<>();
roles.add(em.find(Role.class,2));
user.setRoles(roles);
return user;
}
}
service layer:
package application.service;
import application.controller.CommonAPIController;
import application.dao.UserDAO;
import application.model.User;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
#Service
public class UserServiceImpl implements UserService {
final static Logger LOGGER = Logger.getLogger(UserServiceImpl.class.getName());
private final UserDAO userDAO;
public UserServiceImpl(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
public User addCustomer(User user) {
return userDAO.addCustomerRole(userDAO.addUser(user));
}
}
and controller:
package application.controller;
import application.model.User;
import application.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
public class CustomerAPIController {
private final UserService userService;
public CustomerAPIController(UserService userService) {
this.userService = userService;
}
#PostMapping(value = "/customer/register")
public User addCustomer(#RequestBody #Valid User user){
return userService.addCustomer(user);
}
}
I want to validate field in my User entity, I add validation constraints to Entity and #Valid annotation in controller - next to #RequestBody.
I used this tutorial how to do it: https://mkyong.com/spring-boot/spring-rest-validation-example/
After build I still can send json to /customer/register with payload with empty fields:
{
"firstname": "",
"lastname": "",
"email": "",
"password": "pass"
}
User is successfully registered, although annotations in User entity should not allow to do this?
Do you see what i'm doing wrong?
My project is Spring, in tutorial we have SpringBoot, there's a difference?
Also i have a dao and service layer between entity and controller and i using lombok's #Data annotation.
These details make a difference here or is the error elsewhere?
try to add BindingResults like this
#PostMapping(value = "/customer/register")
public User addCustomer(#RequestBody #valid BindingResults result,User user){
if(results.hasErrors()){
return some error page;
}
else{
return userService.addCustomer(user);
}
Ensure that your controller class is annotated with #Validated
I define UserController and UserRepository and User like this
UserController.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.zusn.domain.User;
import com.zusn.repository.UserRepository;
#RestController
#RequestMapping(value = "/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#RequestMapping(value = "/create", method = RequestMethod.POST)
public User createUser(#RequestBody User newUesr) throws NoSuchAlgorithmException{
User user = userRepository.findByUidAndDevice(newUesr.getUid(), newUesr.getDevice());
if(user == null){
MessageDigest md = MessageDigest.getInstance("SHA");
Long now = System.nanoTime();
md.update(now.byteValue());
String random = RandomStringUtils.randomAlphabetic(32);
md.update(random.getBytes());
newUesr.setConsumerKey(String.valueOf(Hex.encode(md.digest())));
return userRepository.save(newUesr);
}else{
return user;
}
}
}
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.zusn.domain.Devices;
import com.zusn.domain.Providers;
import com.zusn.domain.User;
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
/**
*
* #param uid UID
* #param provider Profider ex) twitter, google+, facebook
* #return User
*/
public User findByUidAndProvider(#Param("uid") String uid, #Param("provider") Providers provider);
/**
*
* #param uid UID
* #param devices Device ex) iOS, Android
* #return User
*/
public User findByUidAndDevice(#Param("uid")String uid, #Param("device") Devices device);
}
User.java
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "uid", nullable = false)
private String uid;
#Column(name = "provider")
private Providers provider;
#Column(name = "device", nullable = false)
private Devices device;
#Column(name = "consumer_key", nullable = false, unique = true)
private String consumerKey;
#OneToOne(cascade = CascadeType.ALL, fetch=FetchType.LAZY)
private Profile profile;
public User() {
super();
}
public User(String uid, Providers providers, String consumerKey) {
super();
this.uid = uid;
this.provider = providers;
this.consumerKey = consumerKey;
}
public String getConsumerKey() {
return consumerKey;
}
public void setConsumerKey(String consumerKey) {
this.consumerKey = consumerKey;
}
public User(Providers provider){
this.provider=provider;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Providers getProvider() {
return provider;
}
public void setProvider(Providers provider) {
this.provider = provider;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public Devices getDevice() {
return device;
}
public void setDevice(Devices device) {
this.device = device;
}
}
When User is not existed, in other words handling first if statement,this method returns new User object. But when User is already existed, it returns status code 500.
And then it didn't print stacktrace when it returns 500 error.
So I'm not sure why it returns 500 error. Please tell me what is wrong this code and why it returns 500 error.
First of all i think you may handle DataAccessException thrown by Spring Data JPA layer. For the 500 error i think it can be a problem of lazy loading. I think it is a different behaviour when you first insert the object entity in database. What server are you using ? Is it a tomcat ? If so how do you monitor your logs ? Depending on your configuration some logs are not visible in the standard catalina.out file. You need to check in localhost log file to see the stack trace.
Without the stacktrace it is hard to guess the problem. Maybe #NoOne is right but maybe you have an unique constrained in the database left from older developments.
If you don't see the stacktrace client side, you can put this snipped to get the stacktrace serverside. because the 5xx error is only telling that smth. went wrong on the server.