我认为我缺少一些核心概念,因为我遇到了几个问题,但让我们从这个问题开始:当User
Subscription
持续存在于数据库中并尝试获取它时使用findOne(id)
,我得到NullPointerException
。我尝试在内部生成的代码中进行深度调试,看起来由于某种原因调用hashCode()
Subscription
个id
对象,这也是因为不明原因只有null
集,而所有其他属性都是{ {1}},但是因为他们(可能)通过调用他们自己的hashCode()
参与hashCode()
方法,所以我得到了这个例外。
基本上我想要的是用户是许多社区的一部分,在每个社区中他都可以创建对其内容的订阅。当我第一次打电话给SubscriptionController
时,一切正常,它会创建User
,Subscription
和Community
,我可以在数据库中看到它们,一切都很好。但是当我在UserRepository.findOne()
内拨打CrudRepository
UserSerivce
时 - 我得到了例外。
我一直试图解决这个问题两个星期而且没有运气,所以我真的希望有人可以花一些时间来帮助我。 以下是课程:
用户:
@Entity
@Data
@NoArgsConstructor
public class User {
@Column(nullable = false)
@Id
private Integer id;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JsonIgnore
Set<Subscription> subscriptions;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "payment_id", referencedColumnName = "id", unique = true)}
)
@JsonIgnore
Set<Payment> payments;
public User(Integer userId) {
this.id = userId;
}
}
订阅:
@Entity
@Data
@NoArgsConstructor
public class Subscription {
@Column
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
private Integer id;
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name = "community_id", nullable = false)
private Community community;
@Column(nullable = false)
private Boolean isActive;
@Column(nullable = false)
private Date endDate;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
joinColumns = {@JoinColumn(name = "subscription_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "payment_id", referencedColumnName = "id", unique = true)}
)
private Set<Payment> payments;
public Subscription(User user, Community community, Boolean isActive) {
this.user = user;
this.community = community;
this.isActive = isActive;
this.endDate = new Date();
}
}
社区:
@Data
@Entity
@NoArgsConstructor
public class Community {
@Column(nullable = false)
@Id
private Integer id;
@OneToMany(mappedBy = "community", fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.REFRESH})
@JsonIgnore
private Set<Subscription> subscriptions;
public Community(Integer communityId) {
this.id = communityId;
}
}
我也为每个人提供服务:
UserService:
@Service
public class UserService implements IService<User> {
@Autowired
private UserRepository userRepository;
@Transactional
public User get(@NotNull Integer userId) {
User user = userRepository.findOne(userId);
if (user == null)
return userRepository.save(new User(userId));
return user;
}
@Override
public User save(@Valid User user) {
return userRepository.save(user);
}
}
SubscriptionService:
@Service
public class SubscriptionService implements IService<Subscription> {
@Autowired
SubscriptionRepository subscriptionRepository;
@Autowired
PaymentRepository paymentRepository;
@Override
public Subscription get(@NotNull Integer id) {
return subscriptionRepository.findOne(id);
}
public Subscription getByUserAndCommunity(@Valid User user, @Valid Community community) {
Subscription subscription = subscriptionRepository.findByUserAndCommunity(user, community);
if (subscription != null)
return subscription;
subscription = new Subscription(user, community, false);
return subscriptionRepository.save(subscription);
}
@Transactional
public Subscription activate(@Valid Subscription subscription, @Valid Payment payment, @Future Date endDate) {
paymentRepository.save(payment);
Set<Payment> payments = subscription.getPayments();
if (payments == null)
payments = new HashSet<>();
payments.add(payment);
subscription.setEndDate(endDate);
subscription.setIsActive(true);
return subscriptionRepository.save(subscription);
}
@Override
public Subscription save(@Valid Subscription e) {
return subscriptionRepository.save(e);
}
}
社区服务:
@Service
public class CommunityService implements IService<Community> {
@Autowired
private CommunityRepository communityRepository;
@Override
@Transactional
public Community get(@NotNull Integer id) {
Community community = communityRepository.findOne(id);
if (community == null)
return communityRepository.save(new Community(id));
return community;
}
@Override
public Community save(@Valid Community community) {
return communityRepository.save(community);
}
}
控制器:
@RestController
public class SubscriptionController {
@Autowired
private SubscriptionService subscriptionService;
@Autowired
private CommunityService communityService;
@Autowired
private PaymentService paymentService;
@PostMapping("/subscribe")
public ResponseEntity<Subscription> subscribe(@RequestParam("communityId") Integer communityId, @RequestBody @Valid Payment payment) {
if(!paymentService.checkPayment(payment))
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(null);
VkAuthentication vkAuthentication = (VkAuthentication) SecurityContextHolder.getContext().getAuthentication();
User user = vkAuthentication.getUser();
Community community = communityService.get(communityId);
Subscription subscription = subscriptionService.getByUserAndCommunity(user, community);
Calendar calendar = Calendar.getInstance();
Date newEndDate = DateUtils.addDays(new Date(), calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
subscription = subscriptionService.activate(subscription, payment, newEndDate);
return ResponseEntity
.status(HttpStatus.OK)
.body(subscription);
}
}
这里有一些堆栈跟踪:
java.lang.NullPointerException: null
at org.hibernate.engine.internal.StatefulPersistenceContext.getLoadedCollectionOwnerOrNull(StatefulPersistenceContext.java:786) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.spi.AbstractCollectionEvent.getLoadedOwnerOrNull(AbstractCollectionEvent.java:58) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.spi.InitializeCollectionEvent.<init>(InitializeCollectionEvent.java:22) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1989) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:570) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:252) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:566) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:135) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:430) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at zhiyest.subscriptionsbackend.domain.User.hashCode(User.java:14) ~[classes/:na]
at zhiyest.subscriptionsbackend.domain.Subscription.hashCode(Subscription.java:15) ~[classes/:na]
at java.util.HashMap.hash(HashMap.java:338) ~[na:1.8.0_111]
at java.util.HashMap.put(HashMap.java:611) ~[na:1.8.0_111]
at java.util.HashSet.add(HashSet.java:219) ~[na:1.8.0_111]
at java.util.AbstractCollection.addAll(AbstractCollection.java:344) ~[na:1.8.0_111]
at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:327) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:234) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:221) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:194) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:249) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at ...
我甚至不明白为什么Subscription.hashCode()
为findOne()
User
时会调用at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
...
at zhiyest.subscriptionsbackend.logging.Logger.logAround(Logger.java:29) ~[classes/:na]
...
at zhiyest.subscriptionsbackend.services.UserService$$EnhancerBySpringCGLIB$$6e00bac4.get(<generated>) ~[classes/:na]
at zhiyest.subscriptionsbackend.security.VkAuthenticationProvider.authenticate(VkAuthenticationProvider.java:23) ~[classes/:na]
at zhiyest.subscriptionsbackend.security.VkAuthenticationProvider$$FastClassBySpringCGLIB$$24f3d662.invoke(<generated>) ~[classes/:na]
...
at zhiyest.subscriptionsbackend.security.VkAuthenticationProvider$$EnhancerBySpringCGLIB$$4d8d8001.authenticate(<generated>) ~[classes/:na]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.authenticateIfRequired(AbstractSecurityInterceptor.java:354) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:229) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
...
。
UPD:
{{1}}
答案 0 :(得分:3)
我猜这个问题是@Data
。
此lombok注释是递归依赖的原因(toString()
和hashcode()
)。
尝试使用@Getter
和@Setter
代替@Data
。
我希望它会有所帮助。
答案 1 :(得分:2)
这似乎是某些版本的Hibernate中的错误(请参见下面的第一篇文章)。如果您有一组嵌套的其他Hibernate实体,则在其hashCode()方法内部访问它们似乎有问题。我通过调试确认了这一点。
您可以手动生成一个哈希/代码等于并删除另一个实体。或者,您也可以在下面的第二篇文章中通过评论建议在Lombok中执行以下操作:
@EqualsAndHashCode(exclude={"subscriptions"})
我之所以说“某物”,是因为我没有足够仔细地阅读您的对象图,以至于看不到应该排除哪个对象。但这是一个简单的解决方案,通常,将对象的辅助内容作为其逻辑标识的一部分是没有意义的。
Hibernate 4.2.20 Object HashCode Method Causing NullPointerException