Say I have following code snippet
#Transactional
public void doSthing(){
// save an enetity to db
SomeClass entityA = new entityA();
mapper.save(entityA);
// I got null here!
Integer id = entityA.getId();
anotherEntity.setVal(id);
otherMapper.upate(anotherEntity)
}
as u see, I need the entityA's id to update another entity, but it's null at that time, if I remove the #Transactional it works, but I want the two operations in tansaction, which mean that i need spring rollback the doSthing() method on any opereation failured.
By default, methods annotated with #Transactional will rollback on any RuntimeException. So you can achieve the rollback by throwing some runtime exception under some condition.
If you want to rollback on any exception just add the following:
#Transactional(rollbackFor=Exception.class)
But what #Delinum said in the comment is true in general, that is, if you invoke a save on a dao/repository it should assign an #Id to the value object that you are saving, making it an entity.
I don't know what is type of your 'mapper' instance, but some implementations could work in a way that when you call save it doesn't change the original object, but rather it returns the persisted object. So instead of this:
mapper.save(entityA);
// I got null here!
Integer id = entityA.getId();
Use this:
Integer id = mapper.save(entityA).getId();
Related
From a method callAndUpdateInB(), Suppose I am calling update() method of class B(#Component), in which I am calling an myRepository.save() method to update some data in db, and in same funtion I am performing some other calls ... and then return the response back to class A.
So the problem is data gets updated in db when class B method update() return the response back to class A method callAndUpdateInB().
But it should have updated it when I have called myRepository.save() in update method of class B().
Why so ?
For Reference, just see this dummy example
class A{
#Autowired
B b;
public void callAndUpdateInB(String arg){
String data = b.update(arg);
// check Updates in Db (True)
// Now data is updated in db
}
}
#Component
class B{
#Transactional(
propagation = Propagation.REQUIRED
)
public String update(String arg){
MyRepository myRepository; // This is abstract class having
// imlementation for the following
// data. (MyRepositoryImpl)
String updatedData = myRepository.save(arg);
// check Updates in Db (False)
// Making some other calls, which need that updated data
// But data is not still updated in db.
// Though here the updated data field is showing that the data is updated, but it
// is not actually updated in the db.
return updatedData;
}
}
The transaction will be commited to the database if the method update finishes successfully.
Therefore you can't see the data before the method returns.
Additionally save does not execute the insert/update statement. This will also happen before transaction commit.
If you want to execute the statements before you have to call saveAndFlush(). BUT will also not commit the transaction and from another transaction you will not see this data as well.
This is the usual and expected transactional behavior in a Spring application using transactions.
Propagation REQUIRED
Support a current transaction, create a new one if none exists. Analogous to EJB transaction attribute of the same name.
and keeps the transaction uncommitted and alive at the end of the annotated method.
If you call your update() twice at the very beginning of the request processing, the first starts a transaction and the second reuses it. If you call your update() twice, one successfully, the other unsuccessfully (on unique constraints or something), both of the changes will be rolled back.
Developers usually expect a transaction to start and end like that. But in some cases, a change needs to be committed/rolled back independently from other changes. If it is your case, you can use Propagation.REQUIRES_NEW: See
https://stackoverflow.com/a/24341843/12656244
I'm using JPA with Hibernate and Spring. I have an entity (Say Employee) with an attribute (Say of type Position) and this attribute is lazy-loaded.
I believe that when you try to access the position attribute, it will be lazy loaded from the DB and this is done inside the transnational method.
Let's say I didn't access the attribute in that transnational method. So if I tried to access it later, I would get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session" which is normal because the session was closed by that transnational method.
At this point, I need it null (or not initialized) wherever I access it later in different method but this is not the case! The question is how can we make it null after committing and closing the session because it is not accessed while the session is open?
Below is a simple code to illustrate the issue.
// In some Service class
#Override
#Transactional(readOnly = true)
public Employee getEmployeeById(Integer id) throws Exception {
Employee emp = employeeDAO.getEmployeeById(id);
// I didn't access the position attribute here because I don't need it for now
return emp;
}
Later I call the above method (Say from some controller):
Employee emp = employeeService.getEmployeeById(904);
System.out.println(emp.getPosition()); // Here, the LazyInitializationException
//would occur, but I need this to be null or at least to prevent the lazy loading,
//thus, avoiding the exception. How?
I think this might be the answer that you're looking for
Hibernate - Avoiding LazyInitializationException - Detach Object From Proxy and Session
Basically
Use Hibernate to check if that field is initialised with Hibernate. isInitialized(fieldName)in the getter and return null if not initialised.
Inside employeeDAO.getEmployeeByIdmethod, create a new Employee object and set the parameters from the one that return from query, which is more work but prevent you to couple your domain to Hibernate.
I am working on Spring JPA. As part of it, I have to update an entity ignoring few attributes. The following code is in effort to implement the update operation.
#Transactional
public void updateDMove(DTCRto jsonRto){
//copyProperties(Object source, Object target, String[] ignoreProperties)
DMove dMoveDB = dMoveRepo.findDMove(jsonRto.getLn(), jsonRto.getDriver(), jsonRto.getType());
DMove dMoveRto = jsonRto.convertToDMove(jsonRto);
BeanUtils.copyProperties(dMoveRto,drayMoveDB, new String[] {"moveId", "created","lastchange","locations","status"});
dMoveRepo.save(dMoveDB);
}
DMove : Model class which needs to be updated.
dMoveRepo : respective repository class.
dMoveRto : incoming object.
dMoveDb : object existing in the database.
moveId : is the PK in the DMove class.
Can anyone suggest me what is the way to implement the update operation in Spring JPA ?
Thanks.
detached entity passed to persist means that hibernate doesn't recognize the entity you passed to update, because dMoveDB isn't a persistent object, you lost that when you used this line BeanUtils.copyProperties(dMoveRto,drayMoveDB, new String[] {"moveId", "created","lastchange","locations","status"});
I suggest you remove the moveId so the entity you try to update keeps its orginal primary key and remains as a persistent object.
One last thing, you have to make sure that the object you get from dMoveRepo.findDMove(...) isn't null
I want to test if created entity has been correctly persisted to database.There is a service integration test for create method:
#SpringApplicationContext({"setting ...."})
public class PersonServiceIntegrationTest extends UnitilsJUnit4 {
#SpringBeanByName
private PersonService personService;
#Test
public void createPerson() {
String name = "Name";
String sname = "Surename";
DtoPerson item = personService.createPerson(name, sname, Arrays.asList( new DtoAddress("Pisek","CZE", true), new DtoAddress("Strakonice", "CZE", false) );
Assert.notNull("Cannot be null", item);
/*
* This assertion fails because of transaction (I suppose) - item is not in
* database right now.
* Why? Returned dto 'item; is not null?
*/
//domain with all fetched related entities, eg. address
Person p = personService.getPerson(item.getIdPerson());
List<Address> addresses = p.getAddresses();
Assert.notNull("Cannot be null", p);
Assert.notNull("Cannot be null", addresses);//return collection of Address
Assert.notFalse("Cannot be emtpty", addresses.isEmpty());
ReflectionAssert.assertPropertyLeniens("City", Arrays.asList("Pisek", "Strakonice"), addresses);
}
}
Is it necessary to test create entity if I use hibernate? Someone can write you try to test low-level hibernate but hibernate has own tests. There is a trivial code above but I can imagine some specific code which persists more entites at same time (eg. one-many plus several one-one relations). And I want to test if relations has been correctly persisted.
Is there a pattern to do test this way? I have a problem, that record is not at database. I don't want to use returned dto (it presents only agregate root entity - person, but it does not say about person basic data (one-many), person address (one-many) etc.)... i want to get persisted record.
What I do to test the persistence is:
1) I create the Domain entity,
2) save it with Hibernate/JPA,
3) flush and clear the hibernate session/entity manager
4) load the entity again with hibernate
5) compare the original entity with the one that I have (re)loaded
so I am pretty sure that the mapping is more or less correct and every thing get persisted
I decided to rework service method for create person.
PersonService is responsible only to create domain entity Person - test will do only test the returned DtoPerson and its values.
PersonService will inject AddressService, PersonBasicDataService, which they have own create methods with collection as parameter. These services will have own test classes and test only returned collection of DtoAddress or DtoPersonBasicData.
Tests will be simply and will solve only own responsibility. :-)
As #Ralph said in comments under his answer - this test case is not about service layer. There is necessary to test domain layer. And what there is a new idea which I do not use in integration tests - tests has own hibernate session.
I have a groovy system configured using tomcat and Oracle 10g.
I have a groovy class which defines an follows: (reduced version)
class ChangeTicket {
static constraints = {
chngNr(nullable:false)
}
String chngNr
}
My controller has defined a save method:
if (changeTicketInstance.validate() && !changeTicketInstance.hasErrors() && changeTicketInstance.save()) {
flash.message = "changeTicket.created"
...
}
As far as I know the save method calls by default the validate method in order to
know if the constraints are fullfilled or not therefore the validate method call is redundant. Anyway, when the save is performed an exception will be thrown if the field chngNr is NULL.
In fact the field cannot be empty (NULL) because I've defined the constraint (nullable:false).
What am I doing wrong here?
Thanks in advance,
Luis
The validate call should fail if chngNr is NULL. Some databases do not consider an empty string ("") null (HSQL). If you are binding chngNr to changeTicketInstance using params from a form it is getting assigned an empty string as a value and in that case you would want your constraint to be:
chngNr(blank:false)
Also, save() wont throw an Exception unless you use save(flush:true). Hibernate queues up the changes and, unless you flush, wont throw an actual exception.
try this:
chngName(blank:false,nullable:false)
:-)