简体   繁体   中英

Hibernate Save Multiple Object using one Dao Function

I have three bean classes: Users , UserDetail and Auth and i am doing in service class

@Override
public void addUser(UserDetail userDetail) {
  Users users=new Users();
  users.setUsername(userDetail.getUsername());
  users.setEnabled(userDetail.isEnabled());
  users.setAgentId(userDetail.getAgentId());

  Auth auth = new Auth();
  auth.setUsername(userDetail.getUsername());
  auth.setAuthority(userDetail.getAuthority());

  userDetailDao.addUser(userDetail, users, auth);
}

and i want to save these all object in Dao class like

  @Override
public void addUser(UserDetail userDetail,Users users,Auth auth)
{
  // TODO Auto-generated method stub
  getSession().saveOrUpdate(userDetail);
  //Here i also want to save 'users' and 'auth' in same transaction..
  getSession().flush();
}

Can it possible to solve you can try it...Thanks.

If you reconstruct your UserDetail class to something like this:

public final class UserDetail
{
    private Users user;
    private Auth auth;

    // Getter and Setter
}

You can just go ahead and store the UserDetail object via Hibernate in the Database.

Of course you need to add the required annotations to the UserDetail class.

Alternativly don't reconstruct UserDetail but create a new class to store both objects in, something like UserDetailDO or UserDetailPersistence or some better name you can totally come up with by yourself.

Just take care with the annotations to set up the relations correctly, like OneToOne or OneToMany.

In your case UserDetail class reference members is used in Users and Auth class, and it can be mapped based on primary key of either UserDetail class or Users class.

So you can re-define those secondary classes(Users and Auth) based on primary key referense of UserDetail class instead of creating objects each time.

Take care of annotations of foreign key references.

Other way of doing this to define base details in a class and extend that class to secondary classes. But most scenarios doesn't work with this approach as the object is created again and again which may have application performance.

The problem is manage your transaction in DAO, the best way is your business layer manage the transaction.

Like this:

class BO {

    doSomething() {
        DaoA daoA = new DaoA();
        DaoB daoB = new DaoB();
        transaction.begin();
        daoA.insert();
        daoB.insert();
        transaction.commit();
    }

}

See this post too: Where should "@Transactional" be place Service Layer or DAO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM