What is difference between save() and update() in Hibernate - java

I am developing user module using jsp/servlet and hibernate. While updating user I was using same save method which is used while adding new user.
User service
public static User updateUserInstance(HttpServletRequest request) {
String id = request.getParameter("userId");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String userName = request.getParameter("userName");
String gender = request.getParameter("gender");
String dob = request.getParameter("dob");
String email = request.getParameter("email");
String userType = request.getParameter("userType");
User user = getUser(Integer.parseInt(id));
System.out.println("User is : "+user);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setUserName(userName);
user.setGender(gender);
user.setDob(dob);
user.setEmail(email);
user.setUserType(userType);
return user;
}
UserDao
public boolean saveUser(User user) {
try{
SessionFactory factory = HibernateUtility.getSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return true;
} catch(Exception e) {
System.out.println(e);
return false;
}
}
public boolean updateUser(User user) {
try{
SessionFactory factory = HibernateUtility.getSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
return true;
} catch(Exception e) {
System.out.println(e);
return false;
}
}
So my service is finding user based on Id and updating user values. After that I was using same save method of userDao and instead of updating that user It is creating new user. So I have created new method called updateUser.
I tried to find difference between save and update and found that save will insert into database if identifier doesn’t exist else it will throw an error. While in my case its not showing any error and creating new user. So I am not able to clearly identify how save and update internally works.
What are the differences between the different saving methods in Hibernate?
My question is quite different. I want to know same but its clear mentioned that in above question that "save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity." I asking same, My object has identifier still its creating new object instead of updating old object.

RTFM.
save():
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.)
update():
Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown.
Summary:
Save is for new things. Hibernate assigns an id as required
Update is for old things. Hibernate uses the id the object as is

Related

2 Objects dependent on each other. What now?

I did this simple Spring Security tutorial. https://www.boraji.com/spring-mvc-5-spring-security-5-hibernate-5-example
Now I want to create a user in my database.
The problem is that I need to create 2 objects dependent on each other and I get
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing:
So What's the solution for this??
public static boolean createUser(byte[] image, String name, String username, String password, String permissions) {
String hashedPassword = new BCryptPasswordEncoder().encode(password);
//check if user already exists
boolean exists = User.checkIfUserExists(username);
//if it doesn't add to database
if(!exists) {
UserRole userRole = new UserRole();
User user = new User();
userRole.setRole(permissions);
userRole.setUser(user);
Database.addToDatabase(userRole);
//user table
user = new User(image, name, username, true, hashedPassword, userRole);
Database.addToDatabase(user);
//user role table
userRole.setUser(user);
Database.updateObject(userRole);
return true;
}
else
return false;
}
//Save the object to the database
public static void addToDatabase(Object object) {
SessionFactory factory = HibernateUtil.GetSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.save(object);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
Basically UserRole already needs to be in db to save User and User needs to be in db to save UserRole.
That exception means exactly what is written. You have a relationship between two objects. For example UserRole has a linked User. But when you are trying to save the UserRole into the database the User object you have attached to it is not yet saved (it is in transient state) so Hibernate's problem is how to save that user role in the database when the user might not exist (it still doesn't have valid ID in the database ).
There are different ways you can deal with that. One of them is to mark the list as Cascade=ALL (or Cascade=SAVE_UPDATE). This way you will bind these two objects and when you save the user it will automatically save the user role. There are pros and cons with that. The "+" is that it is easier and you will have just one save. The "-" is that you have these objects connected and you might save/update an object by mistake if you are not careful.
Another solution would be to first save the User (without the roles). Then save the roles with the user set to the newly saved user (it should have a real ID in the database). Then add the roles to the user and update it. This way you will not save anything with transient values and you will go around that problem. Also do it in a transaction so you don't have bad data if something breaks.

When hibernate sets primary key(id)?

I have this code:
Candidate candidate = new Candidate();
candidate.setName("testUser");
candidate.setPhone("88888");
candidateService.add(candidate);
sessionFactory.getCurrentSession().flush();
return candidate;
CandidateService marked as #Transactional;
Can you explain me why after execution of candidateService.add(candidate);
candidate get id field value.
Maybe it is normally?
candidateService.add(candidate) realization:
public void add(Candidate candidate) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String login = auth.getName();
User user = utilService.getOrSaveUser(login);
candidate.setAuthor(user);
candidateDao.add(candidate);
}
#Override
public Integer add(Candidate candidate) throws HibernateException{
Session session = sessionFactory.getCurrentSession();
if (candidate == null) {
return null;
}
Integer id = (Integer) session.save(candidate);
return id;
}
I thought it happened if candidate in persistent state.
I messed.
Since the ID is primary key of the table candiate,when you add it to database a Id generates and returned by the save method.
If you see docs of save method.
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
Returns:
the generated identifier

role field not stored in database after identitymanager role creation

I'm using seam 2.1.2 security and I create a role using identitymanager by jsf richfaces GUI. in creation process I would add a "description" to role created in database , the creation of role is ok but the description field is not added, I must update the role (in other operation by GUI) to see the description field stored in database. the question is what have I to do to store the "description" filed in creation operation?
bellow is my code:
public boolean createRole(Role role) {
IdentityManager identityManager = IdentityManager.instance();
logger.info("creating role:" + role.getRoleName());
if (identityManager.roleExists(role.getRoleName())) {
return false;
}
if (identityManager.createRole(role.getRoleName())) {
completeRolePersistence(role);
return true;
}
return false;
}
and the completeRolePersistence method:
public void completeRolePersistence(Role role) {
logger.info("setting additional info to role...");
Query query = em.createNamedQuery("UPDT_ADDITIONALS");
query.setParameter("name", role.getRoleName())
.setParameter("description", role.getDescription())
.setParameter("level", role.getRoleLevel());
int updated = query.executeUpdate();
logger.info("roles updated with desc : " + updated);
}
it seem that the query is not executed , i print in log
roles updated with desc : 0
The reason your code does not work is because your update query is executing BEFORE the role is actually inserted into the database, thus it updates nothing.
My advice is to not use the role/user creation methods in IdentityManager. You're better off creating Home components to create/edit your roles and users than having IdentityManager do it for you.
If you however want to pursue this, you need to overwrite JpaIdentityStore, customize the createRole method and have it populate the entity as needed.

JPA: Fetch data from DB instead of Persistance Context

I have a simple User Account application in which the user is able to change his details.
Updating the Database
The Managed Bean's method which takes the form parameters and calls the Service method:
public String changeDetails(){
Date date = DateUtil.getDate(birthDate);
Integer id = getAuthUser().getId();
UserDetail newDetails = new UserDetail(id, occupation, date, originCity, residenceCity, description);
EntityTransaction transaction = getTransaction();
userService.updateDetail(newDetails);
transaction.commit();
return null;
}
The Service Method:
public boolean updateDetail(UserDetail newDetails) {
boolean ok = true;
if (newDetails != null) {
UserDetail user = readDetail(newDetails.getId());
user.setOccupation(newDetails.getOccupation());
user.setOriginCity(newDetails.getOriginCity());
user.setResidenceCity(newDetails.getResidenceCity());
user.setBirth(newDetails.getBirth());
user.setDescription(newDetails.getDescription());
}
return ok;
}
Fetching data from DB
#PostConstruct
public void init(){
userService = new UserService();
sessionController.setAuthUser(userService.read(getAuthUser().getId()));
originCity = getAuthUser().getUserDetail().getOriginCity();
residenceCity = getAuthUser().getUserDetail().getResidenceCity();
occupation = getAuthUser().getUserDetail().getOccupation();
birthDate = DateUtil.getStringDate(getAuthUser().getUserDetail().getBirth());
description = getAuthUser().getUserDetail().getDescription();
}
The problem is that the behavior of this code is different. Sometimes I obtain the desired result: once I submit the new details and call the #PostConstruct init () the new details are printed. Some other times the old details are printed even though the DB entry is updated.
Conclusion: Sometimes the JPA brings me different result from what is in the DB. I guess that this results consist of data from the Persistance Context, data which isn't updated. Is there a way in which I can be sure that the JPA always brings the data directly from the DB? Or is there something I'm missing?
If you are using JPA 2 then #Cacheable(false) on your entity definition should make it read from the DB every time.
You mean is there a way to turn the cache off or empty it before an operation ?
emf.getCache().evictAll();

Working with hibernate/DAO problems

Hello everyone here is my DAO class :
public class UsersDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(UsersDAO.class);
protected void initDao() {
//do nothing
}
public void save(User transientInstance) {
log.debug("saving Users instance");
try {
getHibernateTemplate().saveOrUpdate(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void update(User transientInstance) {
log.debug("updating User instance");
try {
getHibernateTemplate().update(transientInstance);
log.debug("update successful");
} catch (RuntimeException re) {
log.error("update failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting Users instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User findById( java.lang.Integer id) {
log.debug("getting Users instance with id: " + id);
try {
User instance = (User) getHibernateTemplate()
.get("project.hibernate.Users", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
Now I wrote a test class(not a junit test) to test is everything working, my user has these fields in the database : userID which is 5characters long string and unique/primary key, and fields such as address, dob etc(total 15 columns in database table). Now in my test class I intanciated User added the values like :
User user = new User;
user.setAddress("some address");
and so I did for all 15 fields, than at the end of assigning data to User object I called in DAO to save that to database UsersDao.save(user); and save works just perfectly. My question is how do I update/delete users using the same logic?
Fox example I tried this(to delete user from table users):
User user = new User;
user.setUserID("1s54f"); // which is unique key for users no two keys are the same
UsersDao.delete(user);
I wanted to delete user with this key but its obviously different can someone explain please how to do these. thank you
UPDATE :
Do I need to set all 15 fields on User object to delete it like I did with save method ?
Having not looked at Hibernate for quite a while now, I can only hazard a guess at the problem.
It seems that you are creating a User object, but only populating the User ID field, so the persistence layer knows nothing about the actual User.
I would recommend using a retrieve function that can find the User with the given ID, and then pass that User into the delete method.
User u = UsersDao.findById("1s54f");
UsersDao.delete(u);
This should work, as the persistence layer will know about the User, so it has all of the details it needs to perform the delete.
However, a more efficient method would be to find a way of deleting a user by ID, so you do not have to query the database to get the instance of the User and then delete it.
Hope this helps.
Chris
In an ideal world you will have your model's business key as the database primary key and you'll not have this problem. But it ain't so, isn't it?
For you particular problem if you are very much sure that the userID is going to be unique then you can try this (taken from here):
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlDelete = "delete User u where u.userID = :id";
int deletedEntities = s.createQuery( hqlDelete )
.setString( "id", userID )
.executeUpdate();
tx.commit();
session.close();
But let me warn you. This kind of code is not good at all. For example what happens if you decide in future that the column you used in delete is no longer unique? Then you'll run into a very serious bug or a very bad case of refactoring. Either way the fool-proof (may not be efficient & may not be feasible) way is to delete records based on their primary key.
Check out the documentation. Get used to the concept of persistent, transient, and detached instances. To delete an instance, you call
session.delete(persistentInstance)
and to update (although you probably shouldn't need to use it), call
persistentInstance = session.merge(detachedInstance)
Shouldn't need to use update? No, because you just need to load/find an object first, and then modify it. Any modifications you make to a persistent object will automatically be saved back to the database.
In order to delete the user that its ID is "1s54f" you should create a delete HQL as follows:
public void delete(String id) {
log.debug("deleting Users instance");
try {
final String deleteQuery = "delete from User where id = :id";
final Query query = getSession().createQuery(deleteQuery);
final query.setString("id",id);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
Then you can use this method like:
userDao.delete("1s54f");
Hope this helps.
Hibernate is an object-relational mapper, that is, it translates between the world of relational databases and object-oriented Java code. Since primary keys are a database concept, it is hibernate's job to translate them into object-oriented terms (in this case: object identity).
That is, if you pass primary keys to hibernate, you are not using hibernate as intended; calling code should represent persistent data with mapped objects, not primary keys. This also allows hibernate to automatically guard against lost updates by checking version numbers.
The typical pattern therefore is to have the following signature:
interface UserDAO {
void delete(User user);
}
and require the DAOs caller to come up with a persistent object to pass to it. The caller might have such an object lying about from the current or a previous (now closed) session, after all, he did somehow learn about its primary key. If all else fails, you can use session.load(User.class, id) to ask hibernate for a proxy to pass to the delete method. (Note that one shouldn't use session.load if the object might no longer exist in the database.)
It's not necessary fetch a whole entity before removing it, neither create a hardcoded query for delete, nor setting every field in entity.
Maybe better way to do that is setting the id for entity and use Hibernate API itself.
If a specific dao is used to entity User, as described in question, try:
public void remove(Serializable id) throws InstantiationException, IllegalAccessException {
User user = new User();
getSessionFactory().getClassMetadata(getEntityClass()).setIdentifier(user, id, (SessionImplementor) getSessionFactory().getCurrentSession());
getHibernateTemplate().delete(entity);
}
As can be seen, neither unnecessary operation in database is made.
And this can be used in generic flavor if GenericDao is implemented like:
public void remove(Serializable id) throws InstantiationException, IllegalAccessException {
Model entity = entityClass.newInstance();
getSessionFactory().getClassMetadata(getEntityClass()).setIdentifier(entity, id, (SessionImplementor) getSessionFactory().getCurrentSession());
getHibernateTemplate().delete(entity);
}
Both ways, Dao must extend org.springframework.orm.hibernate4.support.HibernateDaoSupport to get advantages.
Here's a fragment of generic:
public class GenericDaoImpl<Model> extends HibernateDaoSupport implements GenericDao<Model> {
private Class<Model> entityClass;
public GenericDaoImpl() {
this.entityClass = (Class<Model>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
/* CRUD are implemented here */
public void remove(Serializable id) throws InstantiationException, IllegalAccessException {
Model entity = entityClass.newInstance();
getSessionFactory().getClassMetadata(getEntityClass()).setIdentifier(entity, id, (SessionImplementor) getSessionFactory().getCurrentSession());
getHibernateTemplate().delete(entity);
}
}

Categories

Resources