简体   繁体   中英

JPA entity not updated when querying from another method in controller

I'm new to Spring-boot and Spring JPA framework. I have a persistent JPA entity ("activeNode") with one-to-many relation with another persistent JPA entity ("activeAudience").

In one of my controller functions, after creating two instances of each, I added the activeAudience entity to the (one-to-many) ActiveAudienceList of the activeNode.

Then, I queried for this activeNode object in its repository using its id, and used the returned object to send a post request to another controller endpoint with data being this activeNode in String form (to display its field values at this point). At this point, in its "ActiveAudienceList" field, there is an active audience instance.

However, I then sent a get request to a third controller endpoint (mapped to another controller function) with the same activeNode's id passed as path variable, and then tried to query for this activeNode again in repository (using its id) then displaying it, but this time the "ActiveAudienceList" field becomes an empty list.

Why is the this ActiveNode entity's field not saved after I tried to query it from repository in another controller function? From my understanding, the ActiveNode instance should be persistant, and therefore any updates on an ActiveNode object itself should be automatically saved in repository. Below are some of my code:

ActiveNode and ActiveAudience entities:

@Entity
@Table
public class ActiveAudience {
    @Id
    @GeneratedValue
    private Long id;
    @ManyToOne(targetEntity = ActiveNode.class)
    @JoinColumn(name="audience_node_id",referencedColumnName = "id")
    private ActiveNode activeNode;
    //getters and setters...
}

@Entity
@Table(name="active_node")
public class ActiveNode {
    @Id
    @GeneratedValue
    private Long id;
    @OneToMany(mappedBy = "activeNode")
    private List<ActiveAudience> activeAudienceList = new ArrayList<>();
    //getters and setters..
}

Repository and DAO:

//ActiveNodeRepository.java:
public interface ActiveNodeRepository extends JpaRepository<ActiveNode, Long> {
    @Query(value="select t from ActiveNode t where t.id=:Id")
    ActiveNode findByActiveNodeId(Long Id);
}
//ActiveAudienceRepository.java:
public interface ActiveAudienceRepository extends JpaRepository<ActiveAudience, Long> {
}
//DAO.java:
@Service
public class DAO {
...
    @Autowired
    private ActiveAudienceRepository activeAudienceRepository;
    @Autowired
    private ActiveNodeRepository activeNodeRepository;
    public ActiveNode addNewActiveNode(ActiveNode node){return activeNodeRepository.save(node);}
    public ActiveAudience addNewActiveAudience(ActiveAudience aud){return activeAudienceRepository.save(aud);}
    public ActiveNode searchActiveNodeById(Long id){return activeNodeRepository.findByActiveNodeId(id);}
...
}

Controller class implementation:

... 
    @Autowired
    private DAO dao;
    @GetMapping(value="/smalltest")
    public void test1(){
//create active node and active audience; associate them
        ActiveNode actn = dao.addNewActiveNode(new ActiveNode());
        ActiveAudience acta = dao.addNewActiveAudience(new ActiveAudience());
        actn.getActiveAudienceList().add(acta);
// when I directly query for the object in this method and display it like this, the "ActiveAudienceList" field has an instance
        restTemplate.exchange("http://localhost:8080/show", HttpMethod.POST,new HttpEntity<>(actn.toString()),String.class);
//But when I call a "intermediate" endpoint and do the same query and display it, the "ActiveAudienceList" becomes empty
      restTemplate.exchange("http://localhost:8080/smalltest2/"+Long.toString(actn.getId()), HttpMethod.GET,new HttpEntity<>(new HttpHeaders()),String.class);
    }

//the "intermediate" endpoint
    @GetMapping(value="/smalltest2/{id}")
    public void test2(@PathVariable("id") Long ID){
        ActiveNode actn = dao.searchActiveNodeById(ID);
        restTemplate.exchange("http://localhost:8080/show2", HttpMethod.POST,new HttpEntity<>(actn.toString()),String.class);
    }

//the following methods are used to display the field values of an entity
    private String str = new String();
    @RequestMapping(value="/show",method= RequestMethod.POST)
    public void showjson(@RequestBody String obj){
        this.str = obj;
    }
    @GetMapping(value = "/show",produces =MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String display(){
        return this.str;
    }

Results of direct querying in the method (where both instances are created): Results of querying in another method: 在此处输入图像描述

You are persisting active node before you add values to its active audience's list. Try setting active audience then persisting likewise:

ActiveNode actn = new ActiveNode();
ActiveAudience acta = dao.addNewActiveAudience(new ActiveAudience());
actn.getActiveAudienceList().add(acta);
dao.addNewActiveNode(actn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM