当Hibernate从数据库

时间:2016-06-16 08:42:50

标签: java hibernate jpa spring-data-jpa

我使用Hibernate和JPA

我有一些POJO

public class Pojo {
  @Temporal(TemporalType.DATE)
  private Date date; 
  @Transient
  private long dLong;
  //other fields
  //getters and setters
}

当我从数据库中获取对象date时,我想将dLong转换为Pojo。 当我有对象时,我可以这样做

Pojo pojo = repository.findFirst();
Date date = pojo.getDate();
long l = date.getTime();
pojo.setDLong(l);

但我想在致电repository.findFirst()时这样做 我试图使用getter和setter但是没有成功。

编辑 热门内容就是例子。抱歉,我无法通过示例解释我的问题。现在我展示我的原始代码:

@Entity
public class Medicament {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    @Transient
    private long date;

    @Temporal(TemporalType.DATE)
    private Date dateExpiration;

    //getters and setters
}

接下来我有服务

@Service
public class MedicamentService {

    @Autowired
    private MedicamentRepositoryEntityGraph medicamentRepositoryEntityGraph;

    public Medicament findById(int id) {
        return medicamentRepositoryEntityGraph.getOne("select m from Medicament m where m.id="+id, "user", "disease");
    }
}

和存储库

@Repository
public class MedicamentRepositoryEntityGraph {

    @Autowired
    private EntityManager entityManager;

    public Medicament getOne(String query, String...param) {
        EntityGraph<Medicament> entityGraph = template(param);
        Medicament medicament = entityManager.createQuery(query, Medicament.class)
            .setHint("javax.persistence.loadgraph", entityGraph)
            .getSingleResult();
        return medicament;
    }

    private EntityGraph<Medicament> template(String... param) {
        EntityGraph<Medicament> entityGraph = entityManager.createEntityGraph(Medicament.class);
        entityGraph.addAttributeNodes(param);
        Map<String, Object> hints = new HashMap<String, Object>();
        hints.put("javax.persistence.fetchgraph", entityGraph);
        return entityGraph;
    }

}

我存储在数据库dateExpiration中,但是当我从数据库&#39; Medicament&#39;我想转换&#39; dateExpiration&#39;长期约会&#39;我在服务findById

中使用方法MedicamentService

我尝试使用getter和setter但未成功:

public void setDateExpiration(Date dateExpiration) {
        this.dateExpiration = dateExpiration;
        this.date = dateExpiration.getTime();
    }

1 个答案:

答案 0 :(得分:0)

Hibernate可能绕过设置者,但你可以使dLong成为虚拟的&#34;财产,例如像这样:

public long getDate() {
  if( dateExpiration == null ) { 
    return -1;
  }

  return dateExpiration.getTime();
}

//Be careful with that and add some documentation
public void setDate(long date) {
  dateExpiration = new Date(date);
}

或者,您可以将date映射到与dateExpiration相同的列,并将insertable = false, updatable = false添加到@Column,但您可能需要添加自定义用户类型才能转换数据库日期很久。