【发布时间】:2014-05-16 15:31:21
【问题描述】:
我在我的项目中使用 Spring-mvc 和 Spring-data-jpa。我有这两个实体
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
}
用户.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);
}
}
到目前为止一切似乎都很好。我将这个 Restfull 服务用于 Android 客户端,我所要做的就是构建一个新的 Location 对象并通过 POST 请求将其发送到正确的 URI。
这是对象的结构:
{
"id":1,
....,
....,
"user":{
"uid":1,
"attr1":"value1",
"attr2":"value2",
.....
}
}
问题:我总是收到 (org.hibernate.exception.SQLGrammarException) 错误(原因:org.postgresql.util.PSQLException:错误:“用户”处或附近的语法错误)
我做错了什么?存储我的位置的最佳方法是什么?
【问题讨论】:
-
你能发布存储库和休眠配置吗
-
存储库配置???
标签: spring spring-mvc spring-data spring-data-jpa spring-data-rest