I have a Hibernate related question . Can I perform multiple saves to a single entity . Do you foresee any problems with this code?
// I create a new object of type Payment that needs to be persisted...
Payment p1 = new Payment();
//Set some values..
p1.setName("abc");
//persist it to DB to retrieve the Id which is autogenerated inorder to relay it to another function..
Payment savedP1 = paymentRepository.save(p1);
int sum = calPaymentSum(savedP1.getId());
//set more values to the same object ...
savedP1.setSum(sum);
//update that object that was saved to DB earlier..
paymentRepository.save(savedP1);
You need to use;
paymentRepository.update(savedP1);
If you use save method, it is inserted to table with new id.
If you are using spring data jpa repository saving an existing entity will automatically update it and your procedure is right.
but in javaEE jpa you need to use merge method of EntityManager in order to update an existing entity.
paymentRepository.merge(savedP1);
Related
We use Hibernate and annotations to map our db and entities. But for some data tables I don't want entity classes (Because these table names and all are keep changing) so that the application will be more dynamic
So is it possible using hibernate to load data from a table without a entity class?
If so how?
Hibernate provides a way to execute SQL query and to map it to an entity or any class : native sql queries.
Use plain JDBC. I'm not sure what you mean by "table names and all are keep changing" but it sounds like a bad idea to me.
What you could do is create the sql query using string concatenation then use plain JDBC to execute it. That way you can keep table names dynamic.
If Persistence class won't be used, then the data encapsulation won't occur thus data can be accessed directly.
Hibernate Queries interact with the POJO class to fetch data.
Query, Criteria, HQL all the classes use the POJO for fetching data.
Hibernate Framework was mainly designed for the ORM Mapping.
Thus without POJO class, not possible to interact with the database.
Thus using JDBC connection would be the option left.
Use Dynamic models introduced in Hibernate 5 version - 5.4.0.Final
Hibernate Dynamic Models
To achieve this you will need HBM files created.
Session s = openSession();
Transaction tx = s.beginTransaction();
Session s = openSession();
// Create a customer
Map david = new HashMap();
david.put("name", "David");
// Create an organization
Map foobar = new HashMap();
foobar.put("name", "Foobar Inc.");
// Link both
david.put("organization", foobar);
// Save both
s.save("Customer", david);
s.save("Organization", foobar);
tx.commit();
s.close();
Here Customer & Organization are table names
Organization is Parent of Customer.
Click on the above link for more details
I'm working in a project right now, here is a piece of code:
public boolean getAll() {
TypedQuery<Tag> query = em.createQuery("SELECT c FROM Tag c WHERE (c.tagName !=?1 AND c.tagName !=?2 AND c.tagName !=?3) ", Tag.class);
query.setParameter(1, "Complete");
query.setParameter(2, "GroupA");
query.setParameter(3, "GroupB");
List<Tag> Tag= query.getResultList();
But when I try to do something like this:
Tag.get(2).setTagName = "Hello";
em.persist(Tag.get(2));
It considers it to be an update instead of a create? How can I make JPA understand that it's not database related, to detach the chains with the Database and create new register only changing its name for example?
Thanks a lot for any help!
Best regards!
EDIT:
Using the em.detach just before changing it values and persisting each of the list worked just fine!
Thanks everyone!
You haven't showed us how you are obtaining your list, but there are two key points here:
everything read in from an EntityManager is managed - JPA checks
these managed objects for changes and will synchronize them with the
database when required (either by committing the transaction or
calling flush).
Calling persist on a managed entity is a no-op - the entity is
already managed, and will be synchronized with the database if it
isn't in there yet.
So the first Tag.get(2).setTagName = "Hello"; call is what causes your update, while the persist is a no-op.
What you need do to instead is create a new instance of your tag object and set the field. Create a clone method on your object that copies everything but the ID field, and then call persist on the result to get an insert for a new Entity.
The decision whether to update or create a new entity object is done based on the primary key. You're probably using an ID on every object. Change or remove it and persist then. This should create a new entry.
If that doesn't work, you might need to detach the object from the Entity Manager first:
em.detach(tagObj);
and persist it afterwards:
em.persist(tagObj);
You can also force an update instead of creation by using
em.merge(tagObj)
There is no equivalent for forced creation AFAIK. persist will do both depending on PK.
I have an detatched entity and want to set some values. But before that I want to refresh the entity to be sure to have the latest data from the database. I came up with this code. It merges and refreshes my entity before setting some new values.
The problem is, that this creates a new object. Is there a better and simpler way to archieve this?
#Entity
public class MyEntity{
public void setValueAndPersist(){
EntityManager em = ...
em.getTransaction().begin();
MyEntity newEntity = em.merge(this);
em.refresh(newEntity);
newEntity.setSomeVal("someVal");
em.commit();
}
}
Use a own class for interaction with database. DONT do this in the entity itself!
Solution1:
You can use #Version for current object. https://weblogs.java.net/blog/2009/07/30/jpa-20-concurrency-and-locking . You get a Exception when its not the newest version and you tried to merge it.
Solution2:
You can use find(...) http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#find%28java.lang.Class,%20java.lang.Object%29
With class and ID from the current Item to load the actual state from DB (or Persistence Context if already exists in it).
I have a object A which maps to table A in DB
class A {
Integer id;
String field2,field2;field3 ,... fieldN;
//lots of other attribute
}
Now i want to write a DAO api that just updates a single field.One approach is that i can first load the object then changes the attribute i need and then use merge api
//start transcation
A a = session.load(A.class, id);
A.setfieldP(newValue)
session.merge(A)
//commit transcation
Now if i use following code
//start transcation
A a = new A();
a.setId(id); //set a id by which object A exists in DB
A.setfieldP(newValue)
session.merge(A)
//commit transaction
Now second approach all fields except id and fieldP are set to null
1)Now is there any other approach?
2)Can i use update instead of merge ?
If you need to update lots of entities at once the most efficient way is to use a query:
Query query = session.createQuery("update EntityName set fieldP = 'newValue' "
+ "where id IN (75, 76)");
query.executeUpdate();
This allows you to change field values without loading the entity or entities into memory.
It is best practice is to use named queries and named parameters - the above implementation is just an example.
I usually prefer session.get vs session.load, as session.get will return null as opposed to throwing an exception, but it depends on the behavior you want.
loading the object, setting your field, and calling either
session.merge(myObject)
is the standard way, although you can also use
session.saveOrUpdate(myObject)
as long as the object hasn't been detached, which in your case, it won't have been detached. Here is a good article explaining the differences in merge and saveOrUpdate.
In your second example, you are editing the primary key of the object? This is generally bad form, you should delete and insert instead of changing the primary key.
Using JPA you can do it this way.
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaUpdate<User> criteria = builder.createCriteriaUpdate(User.class);
Root<User> root = criteria.from(User.class);
criteria.set(root.get("fname"), user.getName());
criteria.set(root.get("lname"), user.getlastName());
criteria.where(builder.equal(root.get("id"), user.getId()));
session.createQuery(criteria).executeUpdate();
One more optimization here could be using dynamic-update set to true for the entity. This will make sure that whenever there is an update, only field(s) which are changed only gets updated.
How do I create persist-able class dynamically and persist it to the Google App Engine datastore
If you mean you don't know beforehand what fields/properties will be persisted then you can use the Datastore API to create and persist entities on the fly.
Entity entity = new Entity("User"); // specify the entity kind
entity.setProperty("name", "someuser"); // add some properties
entity.setProperty("email", "some#user.com");
DatastoreServiceFactory.getDatastoreService().put(entity); //save it
However if you actually want to create 'class' dynamically then this answer would not help.