1.1+n Problem description in Hibernate
In a many-to-one relationship, when we need to query the records of a table of more than one party, we can complete the operation with an SQL statement. However The default value of fetch for the @manytoone callout in a multi-party entity class is Fetchtype.eager, at which point, hibernate emits an n (multiparty record number) SQL statement in addition to the SQL statement that records the table of the one party that queries the many, which is 1+ N problem. such as: BBS's Plate (Category), subject (topic), Reply (msg). A plate has multiple themes, and a theme belongs to a plate, then category and topic belong to a one-to-many relationship, set @manytoone in topic. When all topics need to be removed, only a single statement of SELECT * from topic can be issued. However, hibernate queries the category corresponding to each topic, so 1+n SQL statements are issued.
2. Solutions to 1+n problems
① set the Fetch property value of @manytoone to Fetchtype.lazy, which is resolved after the following N SQL statements are sent on demand. However, one drawback is that cascading objects cannot be obtained if a cascading query is required.
② sets @batchsize (size=5), which is added to the class, and @entity in the same location, so that the issued SQL statements are reduced. This setting improves efficiency to a certain extent.
③ uses join fetch in the HQP statement, which is actually the method used in the criteria. This is also the most commonly used method;
- @Test
- //join Fetch
- publicvoid test1_n3() {
- Session session=sf.getcurrentsession ();
- Session.begintransaction ();
- //list<topic> topics= (list<topic>) Session.createcriteria (Topic.class). List ();//Only one query statement, The criteria method is this way
- List<topic> topics= (list<topic>) session.createquery ("from Topic T left join fetch t.category C"). List ( );
- For (Topic t:topics) {
- System.out.println (T.getid () +"----" +t.gettitle ());
- System.out.println (T.getcategory (). GetName ());
- }
- Session.gettransaction (). commit ();
- }
This is the 1+n problem in hibernate.
1+n problems in Hibernate and how to solve them