我创建了两个实体。一是用户,二是位置。它具有一对多关系,即一个用户将拥有多个位置。

我能够创建用户。现在我想在某个用户下创建一个位置。

我通过 oneToMany 关系映射了两个实体。但我无法从发布的请求中获取用户的 id,因此只有位置值会插入到数据库中,而不是 user_id。

用户:

@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; 
    } 
 
} 

地点:

@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; 
    } 
} 

位置 Controller :

@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(); 
        } 
} 

位置存储库:

import org.springframework.data.repository.CrudRepository; 
 
public interface LocationRepository extends CrudRepository<Location, Long>{ 
 
} 

请求:

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

回应:

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

我尝试通过这种方式获取用户:

  @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); 
     } 

我还尝试使用用户 Crud Repository 的 findById() 方法

  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>{ 
 
}  

然后它要求将 User 转换为用户。当我尝试转换时,方法调用仍然存在问题。

尝试像这样输入:

    { 
"latitude" : 15645.00, 
"longitude" : 154645.00, 
"location" : "dahisar", 
 
"user" : { 
    "id" : "1" 
} 
} 

我该怎么做?我是这方面的初学者,请帮忙谢谢..

请您参考如下方法:

您可能必须设置写入(保存)事务。

Session session=sessionFactory.getCurrentSession(); 
session.beginTransaction(); 
   ... 
   locationRepository.save(newLocation); 
   ... 
   locationRepository.save(newLocation);  
   ... 
   newLocation.setUser(user); 
   ... 
session.getTransaction().commit(); 


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!