Java Hibernate JPA填充瞬态或公式字段
我在实体类中有一个可选的列距离。它并不总是需要填充的,但是对于一些特殊的获取查询来说是必需的。在获取过程中,hibernate不会将其映射为@transient。SqlResultsMapping也不起作用。 我尝试使用@Formula,但在本机查询中有一些输入值 这是后实体类Java Hibernate JPA填充瞬态或公式字段,java,hibernate,spring-boot,jpa,spring-data-jpa,Java,Hibernate,Spring Boot,Jpa,Spring Data Jpa,我在实体类中有一个可选的列距离。它并不总是需要填充的,但是对于一些特殊的获取查询来说是必需的。在获取过程中,hibernate不会将其映射为@transient。SqlResultsMapping也不起作用。 我尝试使用@Formula,但在本机查询中有一些输入值 这是后实体类 @Entity @Table(name = "post") public class Post { @Id @GeneratedValue(strategy = GenerationType.AUTO
@Entity
@Table(name = "post")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty("id")
@Column(name = "post_id")
private int postId;
@JsonIgnore
@Transient
@Column(name = "distance", insertable=false, updatable=false)
private Double distance;
// Other columns and setters getters
}
这是售后服务类方法
@Override
public List<Post> findPostsForUpdatedFeed(Integer id, Double latitude, Double longitude) {
if(latitude != null && longitude != null)
return postDao.findPostsForUpdatedFeed(id, latitude, longitude);
else
return postDao.findPostsForUpdatedFeedWithoutLatLong(id);
}
这是后DAO类方法
// Actual query uses subqueries, joins and union
@Query(value = "(select distinct p.*,(3959 * acos (cos ( radians(:latitude) )* cos( radians( p.post_latitude ) )* cos( radians( p.post_longitude ) - radians(:longitude) )+ sin ( radians(:latitude) )* sin( radians( p.post_latitude ) ) ) ) AS distance\n" +
"from post p where id=:id;", nativeQuery = true)
List<Post> findPostsForUpdatedFeed(@Param("id") Integer id, @Param("latitude") Double latitude, @Param("longitude") Double longitude);
// unlike above query, distance is not calculated here
@Query(value = "(select distinct p.* from post p where id=:id;", nativeQuery = true)
List<Post> findPostsForUpdatedFeedWithoutLatLong(@Param("id") Integer id);
// There are 3 more quries and 2 of them requires distance to be calculated
从距离映射字段Marco中删除@Column注释。我也尝试过删除@Column,看起来只要距离是暂时的,它就不会影响。您想要的是使用暂时的注释来忽略该字段。我不确定是否可以动态地包含或排除字段的注释。现在,Transient不能与您的代码一起工作的原因可能与您包含的相对包有关,请尝试将getter设置为Transient而不是属性,并在此处查看Christoskarapaps。不幸的是,在getter getDistance中设置@Transient不起作用。我得到java.sql.SQLSyntaxErrorException:mappedBy尝试从内部填充帖子时,“字段列表”中的未知列“post0\u0.distance”出错。您可以使用。