使用一对多关系映射从邮递员那里获取输入?春天的Java

Posted

技术标签:

【中文标题】使用一对多关系映射从邮递员那里获取输入?春天的Java【英文标题】:Get input from postman using one to many relation mapping? spring java 【发布时间】:2018-02-27 07:25:13 【问题描述】:

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

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

我通过 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    // 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>

 

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

尝试这样输入:

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

"user" : 
    "id" : "1"


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

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

我没有得到用户。这就是问题所在。 如果您有保存的用户,请检查数据库。如果没有 - 它表明您不提交事务 我创建了一个 id 为 1 的用户。所以它被保存在数据库中。 如果您的数据库中存储了正确的数据,您只需要请求数据库,并且在多个用户注册时它是否正常工作。你用什么数据库? 我正在使用 mysql。如何从我的发布请求中获取用户 ID 并检查用户是否存在并将用户 ID 添加到位置表?

以上是关于使用一对多关系映射从邮递员那里获取输入?春天的Java的主要内容,如果未能解决你的问题,请参考以下文章

hibernate5(10)注解映射[2]一对多单向关联

MyBatis的对象关系映射---一对多等值连接策略★★★★★

一对多关系映射

MyBatis的对象关系映射---一对多N+1策略★★★★★

(转)Hibernate框架基础——一对多关联关系映射

hibernate映射的 关联关系:有 一对多关联关系,一对一关联关系,多对多关联关系,继承关系