为什么在saveandflush之后实体中的id为null但数据库中不为null?

时间:2016-11-19 02:33:59

标签: java oracle hibernate spring-data-jpa id-generation

我使用最新的 Spring Boot Spring Data JPA Hibernate 。使用的数据库是 Oracle 11G 。我一直在寻找解决方案几天但没有任何效果。 我很难检索数据库中新插入(成功)的实体的id 。我使用序列和触发器。 e.g。

实体:

    @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;

查询在控制器中执行。 e.g。

@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”: “一个”}

但是这是System.out.println(已保存)之后的对象;

Address{id=0, addressLine='aa', addressLine2='a', city='a',
postalCode='a'}

存储库:

@Transactional
public interface AddressRepository extends JpaRepository<Address, Long> {
    List<Address> findByCity(String city);
}

我怀疑会话存在问题,数据尚未提交。我对吗?怎么解决?谢谢!

2 个答案:

答案 0 :(得分:1)

问题解决了!

在地址实体中的getter getId之前有一个@Id注释。

刚刚删除了注释

在:

@Id
public long getId() {
    return id;
}

后:

public long getId() {
    return id;
}

答案 1 :(得分:0)

I had a similar problem. I was able to persist entity to db just fine and id value was in db. But when I retrieved the entity via REST interface the id attribute was null. The problkem in my case was due to a side effect of HATEOS support in spring-data-rest where id is not returned as an attribute but instead is returned as a HATEOS self link url. To fix this I had to have the following class in my project:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;

import javax.persistence.EntityManager;
import javax.persistence.metamodel.Type;

@Configuration
public class RepositoryConfig extends RepositoryRestConfigurerAdapter {
    @Autowired
    private EntityManager entityManager;

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(
                entityManager.getMetamodel().getEntities().stream()
                        .map(Type::getJavaType)
                        .toArray(Class[]::new));
    }    
}