1

I have created two entity's. One is User and other is Location. It has one to many relation i.e one user will have multiple locations.

I am able to create the user. Now I want to create a location under some user.

I mapped both entity's by oneToMany relation. But I am not able to get the user's id from the posted request and so only location values are getting insert in the database not the user_id.

User :

@Entity // This tells Hibernate to make a table out of this class
@Table(name = "user") 
public class User {


      public User() {}

      public User(String email, String name) {
            this.email = email;
            this.name = name;
          }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)

    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    private String email;

    private String number;


    @OneToMany(cascade={CascadeType.ALL})
    @Fetch(FetchMode.JOIN)
    @JoinColumn(name="id", referencedColumnName="id")
    private Set<Location> locations;

    public Set<Location> getLocations() {
        return locations;
    }

    public void setLocations(Set<Location> locations) {
        this.locations = locations;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

Location :

@Entity
@Table(name = "location") 
public class Location {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)

    @Column(name ="id")
    private Long id;


    private String location;
    private double latitude;

    public Location() {}

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;


       @Override
    public String toString() {
        return "Location [id=" + id + ", location=" + location + ", latitude=" + latitude + ", longitude=" + longitude
                + "]";
    }
    public double getLatitude() {
        return latitude;
    }
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }
    public double getLongitude() {
        return longitude;
    }
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
    private double longitude;
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public char[] getId() {
        // TODO Auto-generated method stub
        return null;
    }
}

LocationController :

@Controller    // This means that this class is a Controller
@RequestMapping(path="/Locations") // This means URL's start with /demo (after Application path)
public class LocationController {

        @Autowired // This means to get the bean called userRepository
                   // Which is auto-generated by Spring, we will use it to handle the data
        private LocationRepository locationRepository;

        private UserRepository userRepository;


         @RequestMapping("/create")
         @ResponseBody
         public Location create(@RequestBody Location location) {
           String locId = "";
           Location newLocation = new Location();
                   try {

                             locationRepository.save(location);
                             locId = String.valueOf(location.getId());
                       }
                       catch (Exception ex) {
                        // return "Error creating the user: " + ex.toString();
                           return location;
                       }
                       return locationRepository.save(location);
                 }   

        private User userRepository(User user) {
        // TODO Auto-generated method stub
        return null;
    }

        @GetMapping(path="/all")
        public @ResponseBody Iterable<Location> getAllLocations() {
            // This returns a JSON or XML with the users
            return locationRepository.findAll();
        }
}

LocationRepository:

import org.springframework.data.repository.CrudRepository;

public interface LocationRepository extends CrudRepository<Location, Long>{

}

Request :

    {
"latitude" : 15645.00,
"longitude" : 154645.00,
"location" : "dahisar"

}

Response:

    {
    "id": null,
    "location": "dahisar",
    "latitude": 15645,
    "user": null,
    "longitude": 154645
}

I tried to get the user this way :

  @RequestMapping("/create")
     @ResponseBody
     public Location create(@RequestBody Location location) {
       String locId = "";
       Location newLocation = new Location();
       try {
           User user = userRepository(location.getUser()); //Get the parent Object

           newLocation = new Location(); //Create a new Many object
           newLocation.setLatitude(location.getLatitude());
           newLocation.setLongitude(location.getLongitude());
           newLocation.setLocation(location.getLocation());
           newLocation.setUser(user);

           locationRepository.save(newLocation);
           locId = String.valueOf(newLocation.getId());

       }
       catch (Exception ex) {
        // return "Error creating the user: " + ex.toString();
           return newLocation;
       }
       return locationRepository.save(newLocation);
     }

I also tried to use the findById() method of user Crud Repository

  User user = userRepository.findById(location.getUser().getId()); //Get the parent Object from database

                  newLocation.setLatitude(location.getLatitude());
                  newLocation.setLongitude(location.getLongitude());
                  newLocation.setLocation(location.getLocation());
                  newLocation.setUser(user);

                  newLocation = locationRepository.save(newLocation);   
                  locId = String.valueOf(newLocation.getId());


public interface UserRepository extends CrudRepository<User, Long>{

} 

Then it asks to convert the User to the user. When I try to convert still it has issues in the method calling.

Tried to input like this :

    {
"latitude" : 15645.00,
"longitude" : 154645.00,
"location" : "dahisar",

"user" : {
    "id" : "1"
}
}

How can I do this? I so beginner in this, Please help thank you..

Sid
  • 2,792
  • 9
  • 55
  • 111

1 Answers1

0

It is possible that you have to set transactions for write (save).

Session session=sessionFactory.getCurrentSession();
session.beginTransaction();
   ...
   locationRepository.save(newLocation);
   ...
   locationRepository.save(newLocation); 
   ...
   newLocation.setUser(user);
   ...
session.getTransaction().commit();
Grzesiek
  • 715
  • 5
  • 24
  • I dont get the user. That is the issue. – Sid Feb 27 '18 at 08:27
  • Check in the database if you have a saved user. If not - it suggests that you do not commit the transaction – Grzesiek Feb 27 '18 at 08:33
  • I have created one user which has id 1. so it is saved in the database. – Sid Feb 27 '18 at 09:10
  • If you have the correct data stored in the database, all you need to do is ask for the database, and does it work correctly when several users are registered. What database you use? – Grzesiek Feb 27 '18 at 11:02
  • I am using mysql. How do I get the user id from my post request and check if the user is exist and add the user id to location table? – Sid Feb 27 '18 at 11:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165892/discussion-between-sid-and-grzesiek). – Sid Feb 27 '18 at 12:09