0

I have two entities, a State and a Location. A State can have many locations. This mapping should be pretty straightforward.

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

        public Location() {};

        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;         


       @ManyToOne 
       @JoinColumn(name="StateCode")
       private State state;
}

and the State class:

@Entity
@Table(name="States")
public class State {

    private static final Logger log = LoggerFactory.getLogger(State.class);

    public State() {
        locations = new ArrayList<Location>();

    };


      @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER,    mappedBy="location")    
     private Collection<Location> locations;

    @Id
    @Column(name="StateCode", nullable=false, length=6)   
    private String stateCode;


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

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


    public String getStateCode() {
        return stateCode;
    }

    public void setStateCode(String code) {
        this.stateCode = code;
    }

and yet I get this error: AnnotationException mappedBy reference an unknown target entity property: net.rallaesystems.vibracheck.model.Location.location in net.rallaesystems.vibracheck.model.State.locations

I have followed the advice of changing the mapping to the 'state' field. With this code, though

@Repository
public interface StateRepository extends CrudRepository<State, String>{     
    List<State> findAll();
}

being called in a simple controller, the serialization of States goes into an infinite loop. Maybe there is a problem with the serialization library? I think it is Jackson.

voam
  • 1,006
  • 13
  • 24
  • The following post helped with the serialization issue: http://stackoverflow.com/questions/30423259/jpa-bidirectional-relationship-infinite-loop-circular-reference When I had set up the mapping and when I was getting the serialization error I had assumed the problem was with the mapping and led me to try all sorts of things. This answer was clear. Thanks. – voam Dec 20 '16 at 03:12

2 Answers2

0

You should update the @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="location") to @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="state"), this indicate the state is the owner

where the state is present in your Location class

 @ManyToOne 
 @JoinColumn(name="StateCode")
 private State state;
Liping Huang
  • 4,378
  • 4
  • 29
  • 46
0

Yes, as somebody answered, you need use a valid property of the Location which is a foreign key on the location table (here its state property of location class, and statecode is foreign key in the location table).

Kiran Kumar
  • 1,033
  • 7
  • 20