Pits Tread by jpa Using manyToOne of opntional=true and Solutions

  • 2021-11-29 07:11:19
  • OfStack

Directory jpa Use manyToOne (opntional=true) Pit @ ManyToOne for 1-to-many situations @ manytoone Setting to optional=true Doesn't Work @ manytoone Reason

jpa uses manyToOne (opntional=true) to step on the pit

@ ManyToOne for 1-to-many cases

(By default, it is lazy to load, so there is no need to configure it.) For example, one account can correspond to multiple accountPrivilege


@Entity
@Table(name = ACCOUNT_PRIVILEGE)
 
public class AccountPrivilege extends EntityId {
    //  Account number 
    @ManyToOne(optional = false)
    @JoinColumn(name = ACCOUNT_PRIVILEGE_ACCOUNT, nullable = false)
    private Account account;
}

But adding @ ManyToOne (optional=false) causes some problems.

jpa sets the database field to 0 by default. When querying, the database cannot find the record of account. id=0! !

By consulting 1 data, it is found that:

The optional attribute defines whether the association class must exist. When the value is false, both sides of the association class must exist. If the maintained end of the relationship does not exist, the query result is null.

When the value is true, the relationship maintainer may not exist, and the query result will still be returned to the relationship maintainer. In the relationship maintainer, the attribute pointing to the relationship maintainer is null. The default value for the optional property is true.

The optional attribute actually specifies the join query relationship between the associated class and the associated class. For example, when optional=false, the join query relationship is inner join, and when optional=true, the join query relationship is left join.

It is convenient to use @ ManyToOne or @ ManyToOne (optional=true) in cases where we do not guarantee the existence of record 1 associated with this field.

After I changed @ ManyToOne (optional=false) to @ ManyToOne, jpa defaults that database field to null.

Setting @ manytoone to optional=true does not work

@manytoone

The default value for the optional property is true.

The optional attribute actually specifies the join query relationship between the associated class and the associated class. For example, the join query relationship is inner join when optional=false, and the join query relationship is left join when optional=true.

But in practice, statement 1 straight to innerjoin and setting it to optional=true doesn't work

Cause

dc. createAlias ("org", "org"); Originally written in User user = UserUtils. getUser (); Below, it is correct if removed


public Page<Site> find(Page<Site> page, Site siteMain) {
DetachedCriteria dc = siteMainDao.createDetachedCriteria();
//  Judge whether it is the master station or super administrator 
User user = UserUtils.getUser();
return siteMainDao.find(page, dc);
}

Related articles: