问题描述
我正在使用标准的 Spring CrudRepository。尝试更新记录时,即使为主键分配了非空值,也会创建新记录。
对我做错了什么有什么建议吗?
谢谢, 蒂莫西
软件版本
- Spring Boot 2.4.0
- 数据库 postgres 9.6.17
要保存的实体
python3 mycode.py
服务层中的保存方法
@Entity
@Table(name = "dc_motor")
public class DcMotor implements Serializable,DatabaseEntity {
private static final long serialVersionUID = 4015060163435939638L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version
private Integer version;
// other fields here
// does NOT define equals() nor hashCode()
}
日志输出
@Override
public DcMotorRest saveMotor(DcMotorRest motorToBeSaved) throws MotorNotFoundException {
if (motorToBeSaved.getId() != null) {
Optional<DcMotor> motor = dcRepo.findById(motorToBeSaved.getId());
if (!motor.isPresent())
throw new MotorNotFoundException(
"DC Motor with ID [%d] not found. Unable to update. Use empty / null id to create a new DC Motor"
.formatted(motorToBeSaved.getId()));
}
// troubleshooting code
DcMotor t = new DcMotor(motorToBeSaved);
if (t.getId() == null) {
logger.debug("ID is null in motor to be saved");
} else {
logger.debug("ID is [{}] in motor to be saved",t.getId());
}
DcMotor savedMotor = dcRepo.save(t); // dcRepo extends CrudRepository<DcMotor,Long>
// DcMotor savedMotor = new DcMotor(motorToBeSaved);
return new modelmapper().map(savedMotor,DcMotorRest.class);
}
解决方法
你需要使用
Below method will help in getting contact name when using phone number or email id
public static String fetchContactNameFromContacts(Context context,final String phoneOrEmail) {
String name = phoneOrEmail;
Uri uri;
try {
if (ContextCompat.checkSelfPermission(context,READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"permission granted");
String contactName = "";
if(isValidMobile(phoneOrEmail)) {
Log.d(TAG,"its phone number");
uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneOrEmail));
}else {
Log.d(TAG,"its email id");
uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,Uri.encode(phoneOrEmail));
}
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
Cursor cursor = context.getContentResolver().query(uri,projection,null,null);
if (cursor != null) {
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
if (contactName == null) {
return name;
}
if (contactName.isEmpty()) {
return name;
}
}
}
} catch (Exception e) {
}
return name;
}
更新那个实例然后调用
var inDb = dcRepo.findOne(motorToBeSaved.getId());
另一种方法是使用 dcRepo.save(inDb);
https://stackoverflow.com/a/62925149/14072498
是的,问题出在这里:
DcMotor t = new DcMotor(motorToBeSaved);
基本上它是你创建的一个对象,Hibernate 不知道它,所以它被认为是一个新对象。您需要先在数据库中找到该实体,更新它然后保存。