2
我使用最新的彈簧引導與data-jpa和休眠。使用的數據庫是Oracle 11G。我一直在尋找解決方案几天,但沒有任何工作。 我努力要檢索新插入(成功)在數據庫中的實體的ID。我使用一個序列和一個觸發器。例如爲什麼saveandflush後實體中的id爲null,但數據庫中爲null?
實體:
@Entity
public class Address implements Serializable {
@Id
@Column(name = "ID", nullable = false, precision = 0)
@SequenceGenerator(name = "SEQ_ID_GEN", sequenceName = "GI2S1.SEQ_ID", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ID_GEN")
private long id;
private String addressLine;
private String addressLine2;
private String city;
private String postalCode;
@Id
public long getId() {
return id;
}
Getters & setters omitted...
觸發:
CREATE OR REPLACE TRIGGER SEQ_ADDRESS_TRIG
BEFORE INSERT ON ADDRESS
FOR EACH ROW
BEGIN
SELECT SEQ_ID.nextval
INTO :new.id
FROM dual;
END;
/
序列:
CREATE SEQUENCE SEQ_ID START WITH 1 INCREMENT BY 1 MINVALUE 1;
該查詢在控制器執行。例如
@Controller
@RequestMapping("/address")
public class AddressController {
@Autowired
private AddressRepository addressRepository;
@Transactional
public Address saveAddress(Address address) {
try {
return addressRepository.saveAndFlush(address);
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
@PostMapping("/create")
public String create(@ModelAttribute Address address) {
Address saved = saveAddress(address);
long id = saved.getId();
System.out.println(saved);
return (id > 0) ?
"redirect:/address/find?id=" + id
:
"redirect:/address/list";
}
後的findAll
{ 「ID」 的結果是:81, 「addressLine」: 「AA」, 「addressLine2」: 「一」, 「城市」: 「一」,」 postalCode「:」a「}
但這裏是System.out.println(保存)後的對象;
地址{ID = 0,addressLine = 'AA',addressLine2 = 'A',城市= 'A', POSTALCODE = 'A'}
存儲庫:
@Transactional
public interface AddressRepository extends JpaRepository<Address, Long> {
List<Address> findByCity(String city);
}
我懷疑會話有問題,數據不只是提交。我對嗎?如何解決它?謝謝!
爲什麼會出現這種解決這一問題? –