我正在使用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
}
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);
}
}
直到现在一切似乎都很好。我将这个Restfull服务用于Android客户端,我所要做的就是创建一个新的Location对象并通过POST请求将其发送到正确的URI。
这是对象的结构:
{
"id":1,
....,
....,
"user":{
"uid":1,
"attr1":"value1",
"attr2":"value2",
.....
}
}
问题:我总是遇到(org.hibernate.exception.SQLGrammarException)错误(由以下原因引起:org.postgresql.util.PSQLException:错误:语法错误在或附近&#34;用户&#34)
我做错了什么?什么是存储我的位置的最佳方法?
答案 0 :(得分:0)
该异常表明生成了无效的SQL语句
org.postgresql.util.PSQLException: ERROR: syntax error at or near "user"
尝试重命名列&#39;用户&#39;用户&#39;用户&#39;是Postgres中的保留字,所以不是
@JoinColumn(name ="user")
使用类似
的内容@JoinColumn(name ="user_location")