当前位置:网站首页>Analysis and solution of lazyinitializationexception
Analysis and solution of lazyinitializationexception
2022-07-04 00:34:00 【Teng Qingshan】
Introduce
If FetchType.LAZY, Then when transmitting data to the front end, there may be LazyInitializationException abnormal , Because the session is closed in the service , therefore JSON Mapper Object Unable to get data .
Take an example , We will use the following entities :
When executing the following code :
List<PostComment> comments = null;
EntityManager entityManager = null;
EntityTransaction transaction = null;
try {
entityManager = entityManagerFactory()
.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
comments = entityManager.createQuery(
"select pc " +
"from PostComment pc " +
"where pc.review = :review", PostComment.class)
.setParameter("review", review)
.getResultList();
transaction.commit();
} catch (Throwable e) {
if (transaction != null &&
transaction.isActive())
transaction.rollback();
throw e;
} finally {
if (entityManager != null) {
entityManager.close();
}
}
try {
for(PostComment comment : comments) {
LOGGER.info(
"The post title is '{}'",
comment.getPost().getTitle()
);
}
} catch (LazyInitializationException expected) {
assertEquals(
"could not initialize proxy - no Session",
expected.getMessage()
);
}
Hibernate Will throw out LazyInitializationException, Because the relationship is marked :EntityManagerPostFetchType.LAZY, In obtaining PostComment Object is not loaded in time Post, When the entity gets later Post The session has been closed .
solve
According to design 、 Performance is different from that of developers , There are two common options to solve this problem :
The simplest one is to use FetchType.EAGER, In this way, the session is still alive at the controller method , But it affects performance .
Another way is to use
FetchType.LAZYWith a mapper( Such as MapStruct) take Entity Object conversion DTO object , Then return it to controller, Therefore, if the session is closed, there will be no exception .( This method is suitable for you only want to read or hide some properties of the object from the result , If you need to modify database records, you still have to use entities Entity.)
Here is a simple example :
@RestController
@RequestMapping("/api")
public class UserResource {
@GetMapping("/users")
public Page<UserDTO> getAllUsers(Pageable pageable) {
return userService.getAllUsers(pageable);
}
}
@Service
@Transactional
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllUsers(Pageable pageable) {
return userRepository.findAll(pageable).map(UserDTO::new);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, String> {
Page<User> findAll(Pageable pageable);
}
public class UserDTO {
private Long id;
private String firstName;
private String lastName;
private String email;
private Set<String> addresses;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this.id = user.getId();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
this.addresses = user.getAddresses().stream()
.map(Address::getAddress)
.collect(Collectors.toSet());
}
// Getters, setters, equals, and hashCode
}
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String firstName;
@Column
private String lastName;
@Column(unique = true)
private String email;
@OneToMany(mappedBy = "address", fetch = FetchType.LAZY)
private Set<Address> addresses = new HashSet<>();
// Getters, setters, equals, and hashCode
}
@Entity
@Table(name = "address")
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String address;
@ManyToOne
@JsonIgnoreProperties(value = "addesses", allowSetters = true)
private User user;
// Getters, setters, equals, and hashCode
}
You can see , When invoking the service layer getAllUsers Method returns UserDTO object , And in the UserDTO Object's constructor method , Called user.getAddresses() Method , So even after session close ,dto Objects already exist address attribute , call getAddress No LazyInitializationException Of .
From :
The best way to handle the LazyInitializationException - Vlad Mihalcea
hibernate - Difference between FetchType LAZY and EAGER in Java Persistence API? - Stack Overflow
边栏推荐
- Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
- [CSDN Q & A] experience and suggestions
- Several ways to set up a blog locally [attach relevant software download links]
- 1214 print diamond
- Distributed transaction -- middleware of TCC -- selection / comparison
- Severity code description the project file line prohibits the display of status error c4996 fopen ('fscanf ', StrCmp): this function or variable may be unsafe The most comprehensive solution
- [2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections
- Solution to the impact of Remote Code Execution Vulnerability of log4j2 component on December 9, 2021
- Interview script of Software Test Engineer
- Smart fan system based on stm32f407
猜你喜欢

The difference between objects and objects

2022 system integration project management engineer examination knowledge points: software development model
![[CSDN Q & A] experience and suggestions](/img/db/dff3173dda24ca5740729b54a81153.jpg)
[CSDN Q & A] experience and suggestions

It is worthy of "Alibaba internal software test interview notes" from beginning to end, all of which are essence

Makefile judge custom variables

Briefly understand the operation mode of developing NFT platform
![Docking Alipay process [pay in person, QR code Payment]](/img/30/665580241020ee3adb872e725f0624.jpg)
Docking Alipay process [pay in person, QR code Payment]

STM32 GPIO CSDN creative punch in

Smart fan system based on stm32f407
![[PHP basics] session basic knowledge, application case code and attack and defense](/img/f5/713d7044a693ef23e3fbb1ff9bc9f4.jpg)
[PHP basics] session basic knowledge, application case code and attack and defense
随机推荐
Understanding of Radix
Yyds dry goods inventory three JS source code interpretation - getobjectbyproperty method
挖财帮个人开的证券账户安全吗?是不是有套路
Double efficiency. Six easy-to-use pychar plug-ins are recommended
[Mongodb] 2. Use mongodb --------- use compass
What is the future of software testing industry? Listen to the test veterans' answers
Collation of the most complete Chinese naturallanguageprocessing data sets, platforms and tools
Is the securities account opened by Caicai for individuals safe? Is there a routine
STM32 GPIO CSDN creative punch in
[cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
[about text classification trick] things you don't know
Why use get/set instead of exposing properties
Global and Chinese markets for blood and liquid heating devices 2022-2028: Research Report on technology, participants, trends, market size and share
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
Pair
Several ways to set up a blog locally [attach relevant software download links]
Development and application of fcitx functional plug-ins
The culprit of unrestrained consumption -- Summary
不得不会的Oracle数据库知识点(四)
Vscode regular match replace console log(.*)