I have problem with using EntityManager.persist(Object)
method. Now when i get rid of other problems, by app work without Exception but object is not put in my data
You can open the new Transaction and then commit your records.
@PersistenceUnit(unitName = "NameOfPersistenceUnit")
private EntityManagerFactory entityManagerFactory;
void someMethod(AccountCommodity accountCommodity){
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(accountCommodity);
entityManager.flush();
entityManager.getTransaction().commit();
entityManager.close();
}
You will need to assign id generation strategy as below:
@Entity
@Table(name ="Chain")
public class Chain implements Serializable{
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(name = "date")
private Date date;
@Column(name = "name")
private String name;
//setters and getters
}
and in save method
public int saveChain(Chain chain) {
chain.setDate(new Date());
//chain.setId((long)44); remove this line
Boolean a;
em.persist(chain);
return 222;
}
if you assign Id, then hibernate/jpa will try to update record, which is not available, instead of inserting new record and I think will not throw exception.
Adding these to your web.xml
may solve this problem:
<!-- Open Entity Manager in View filter -->
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Use @EnableTransactionManagement in AppConfig Configuration file header
Can you post what exception are you getting? I will assume that your error is that your persistence.xml you don't specified your "Chain" Object.
You can specify using this tag
<exclude-unlisted-classes>false</exclude-unlisted-classes>
Or just
<class>your.package.Chain</class>
Put this above provider tag.
Also, never set a number for a column tagged as @Id
When you use method save() with a Id column with setted value, hibernate will try to UPDATE NOT INSERT your data.
Do this: Create getEntityManager Method
public EntityManager getEntityManager() {
return entityManager;
}
Then
@Transactional
public void saveChain(Chain chain) {
chain.setDate(new Date());
getEntityManager().persist(chain);
}
solved my problem using
org.springframework.transaction.jta.JtaTransactionManager
hope this work!