我将最新的Spring Boot与Spring Data JPA和Hibernate一起使用。使用的数据库是Oracle 11G。几天来我一直在寻找解决方案,但没有任何效果。我努力检索数据库中新插入(成功)的实体的 id。我使用序列和触发器。例如
实体:
@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":"a","city":"a","postalCode":"a"} 之后的结果
但这是 System.out.println(saved); 之后的对象。
Address{id=0, addressLine='aa', addressLine2='a', city='a',
postalCode='a'}
存储库:
@Transactional
public interface AddressRepository extends JpaRepository<Address, Long> {
List<Address> findByCity(String city);
}
我怀疑会话存在问题,数据尚未提交。我对吗?如何解决?谢谢!