【发布时间】:2021-06-01 18:25:44
【问题描述】:
下面的 java spring boot 代码表示对 java 后端的简单 rest 调用,该后端在 mysql 数据库上执行插入,但是当它执行 rest 调用时,我报告了下面的错误,我无法定义问题出在哪里在mysql db中插入时,如何解决控制台中hibernate表示的错误?谢谢
错误消息休眠:
"could not execute statement; SQL [n/a]; constraint [null];
nested exception is org.hibernate.exception.ConstraintViolationException:
could not execute statement
控制器:
@PostMapping("/newuser")
public User createUser(@Valid @RequestBody User userDetails) {
System.out.println("Sono nella creazione dell'utente");
return userRepository.save(userDetails);
}
型号:
@Entity
@Table(name = "users")
@EntityListeners(AuditingEntityListener.class)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "email_address", nullable = true)
private String email;
/**
* Gets id.
*
* @return the id
*/
public long getId() {
return id;
}
/**
* Sets id.
*
* @param id the id
*/
public void setId(long id) {
this.id = id;
}
/**
* Gets first name.
*
* @return the first name
*/
public String getFirstName() {
return firstName;
}
/**
* Sets first name.
*
* @param firstName the first name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets last name.
*
* @return the last name
*/
public String getLastName() {
return lastName;
}
/**
* Sets last name.
*
* @param lastName the last name
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Gets email.
*
* @return the email
*/
public String getEmail() {
return email;
}
/**
* Sets email.
*
* @param email the email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets created at.
*
* @return the created at
*/
/**
* Sets created at.
*
* @param createdAt the created at
*/
/**
* Gets created by.
*
* @return the created by
*/
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
存储库
import xxx.mode.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* The interface User repository.
*
* @author xxxx
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {}
【问题讨论】:
标签: java spring spring-boot