我在我的項目中使用Spring-mvc & Spring-data-jpa。我有這兩個實體Spring MVC:使用ManyToOne/OneToMany關係存儲數據
Location.java:
@Entity
@Table(name = "location")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Location {
@Id
@GeneratedValue
private int id;
// other attributes...
@ManyToOne(optional=true)
@JoinColumn(name ="user")
@JsonBackReference
private User user;
@ManyToOne(optional=true)
@JoinColumn(name ="client")
@JsonBackReference
private Client client;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// getters & setters
}
User.java:
@Entity
@Table(name = "users")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
@Id
@GeneratedValue
private int uid;
// other attributes...
@OneToMany(mappedBy="user")
@JsonManagedReference
private List<Location> locations;
// getters & setters...
@JsonIgnore
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
}
什麼我想要做的是增加一個新的位置,並將其鏈接到現有用戶。對於這兩個實體都有一個存儲庫和一個服務。 LocationRepository.java:
public interface LocationRepository extends CrudRepository<Location, Integer> {
List<Location> findAll();
//....
}
LocationService.java
@Service
public class LocationService {
@Autowired
private LocationRepository locationRepository;
public List<Location> findAll() {
return locationRepository.findAll();
}
public void save(Location location) {
locationRepository.save(location);
}
@Secured("ROLE_ADMIN")
public void delete(int locationId) {
locationRepository.delete(locationId);
}
}
ApiController.java
@Controller
@RequestMapping(value = "/rest/api")
public class ApiController {
@Autowired
UserService userService;
@Autowired
LocationService locationService;
// Storing a new location
@RequestMapping(value = "/locations/checkin", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> checkin(@ModelAttribute("location") Location location) {
locationService.save(location);
List<Location> locationslist = locationService.findAll();
return new ResponseEntity<List<Location>>(locationslist, HttpStatus.OK);
}
}
一切似乎罰款至今。我爲Android客戶端使用Restfull服務,我所要做的就是重新構建一個新的Location對象,並通過POST請求將其發送給正確的URI。
這是對象的結構:
{
"id":1,
....,
....,
"user":{
"uid":1,
"attr1":"value1",
"attr2":"value2",
.....
}
}
問題:org.postgresql.util.PSQLException:我總是得到一個(org.hibernate.exception.SQLGrammarException)誤差(產生的原因:錯誤:在「用戶」或其附近的語法錯誤)
我做錯了什麼?什麼是存儲我的位置的最佳方法?
你可以發佈存儲庫和休眠配置以及 – ikumen
回購配置配置? –