ETA an explanation of what this is supposed to do.
An employee has to keep track of 2 weeks worth of activities.
Each week(tqiActivitySheetActionBean) contains 7 days (tqiDayActionBean).
Each day contains tasks for that day(tqiTasks)
Tasks are displayed one week at a time(so the employee can switch between this week and last week).
What I did was use an enum to iterate over the week - creates a dataTable of tqiActivitySheetActionBeans and iterate over those in a nested dataTable.
The employee needs to be able to add, delete and edit tasks for each day in place(in the dataTable). I wrapped the tqiTasks in the tqiDayActionBean to group them.
I posted this over at the Seam website, but I'm not getting any bites, I've tried everything I know and some stuff I don't to get this working, but so far no joy.
There's configuration information for Jboss 5 using EJB's, Jboss 4 without. I have an exploded WAR using Jboss 5 and Seam 2.2.0, and no EJB's. I cannot inject an entityManager into my action POJOs.
I tried removing the persistence-unit-ref-name reference from web.xml, added and removed
<transaction:entity-transaction />
<transaction:ejb-transaction />
tags from components.xml (with and without entity-manager="#{entityManager}") . The app won't load when I use either of these.
Used the default values and hardcoded them one at a time. I still can't get this to work.
I'm currently using this configuration:
persistence.xml:
<persistence-unit name="myEmployee" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/myEmployeeDatasource</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.default_schema" value="MY_PROD"/>
<!-- Only relevant if Seam is loading the persistence unit (Java SE bootstrap) -->
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
<!-- this binds emf to jndi under java namespace - but only for jboss prior to 5.0 - I shouldn't need this. -->
<property name="jboss.entity.manager.factory.jndi.name" value="java:/EntityManagerFactories/myEmployee"/>
</properties>
</persistence-unit>
components.xml:
<persistence:managed-persistence-context name="entityManager"
persistence-unit-jndi-name="java:/EntityManagerFactories/myEmployee"
auto-create="true"/>
This deploys and starts correctly, but entityManager is still null.
I have a bunch of EntityHome classes in the same package, these can use an entityManager with no problem. All the docs I've looked at state that I should be able to inject an entityManager, I've followed the configuration info from the Seam docs page, the Seam in Action book and the Seam wiki for JBoss 5 (Seam wiki)
I've set breakpoints in the ManagedPersistence class - where it looks like I have an entityManager right up to the time I want to use it, added #Transactional annotations to the class and method. Still nothing. I can get an EM using
(EntityManager)Component.getInstance("entityManager")
But then I have no transactional access to the underlying entityBean and end up with hibernate LazyInitializationExceptions.
I've been using Seam for almost a year now and I have yet to get this to work. Up til now using the Component method has worked, but There must be something fundamentally wrong with our setup that I cannot get injection to work.
I'd appreciate any help.
ETA code for user classes.
The entity class is TQITask. TQIDayActionBean class is supposed to handle the CRUD for a group of TQITasks for one day, TQIActivitySheetActionBean handles the TQIDayActionBeans for one week.
entity bean:
#Entity
#Table(name = "TQI_TASK")
#Name("tqitask")
public class TqiTask implements java.io.Serializable {
static Logger log = Logger.getLogger(TqiTask.class);
private Integer sysid;
private TqiActivitySubtype tqiActivitySubtype;
private TqiActivityType tqiActivityType;
// ... more fields, getters and setters
dayActionBean(a days tasks):
#Name("tQIDayActionBean")
#Transactional(TransactionPropagationType.REQUIRED) //this is latest attempt
#Scope(ScopeType.CONVERSATION)
public class TQIDayActionBean implements Serializable {
static Logger log = Logger.getLogger(TQIDayActionBean.class);
#In(required=true)
EntityManager entityManager;
//this doesn't work either
#DataModel("tqiTasksForOneDay")
#Out(required = false)
private List<TqiTask> tqiTasksForOneDay;
// .... more stuff
// method that should get an entityManager
/**
* tasks are children of tqiActivitySheet, info we need is in tqiActivitySheetV, so use peopleSoftIdSelected and weekSelected.weekSysid
* to get the tqiActivitySheet sysid needed to load the right tasks
* TODO for now lets just get it straight from the db
*/
#SuppressWarnings("unchecked")
#Begin(flushMode=FlushModeType.MANUAL)
public void generateTasksForDayOfWeek() {
log.debug("date to search for: " + this.tqiTaskDate);
this.tqiTasksForOneDay = this.entityManager.createQuery("SELECT t from TqiTask t where t.workDate = ?1 AND t.activitySheetSysid = ?2 order by t.sysid")
.setParameter(1, this.tqiTaskDate).setParameter(2, this.activitySheetSysid).getResultList();
}
getter/setters etc ...
activitySheetActionBean(a week's dayActionBeans):
/**
* handle the activity sheet weekly code generation here
*/
#Name("tqiActivitySheetActionBean")
public class TQIActivitySheetActionBean implements Serializable{
static Logger log = Logger.getLogger(TQIActivitySheetActionBean.class);
// tried it here first
// #In
// EntityManager entityManager;
#Out(value="tqiDayActionBeansForTheWeek", required=false)
List<TQIDayActionBean> tqiDayActionBeansForTheWeek;
// List<DaysOfTheWeek> daysOfTheWeekEnum;
private BigDecimal currentlySelectedWeekActivitySheetSysid;
#PostConstruct
public void init(){
log.debug("calling init");
this.tqiDayActionBeansForTheWeek = new ArrayList<TQIDayActionBean>();
this.updateDataWhenWeekChanges();
}
getters/setters more stuff ....
The bean named tQIDayActionBean of class TQIDayActionBean cannot be instantiated with new, and there is absolute no way to have a List<TQIDayActionBean> in the application.
This bean, like any other Seam managed bean, can only be injected with #In or instantiated with Component.getInstance(). In the second case (that is with Component.getInstance()) you should understand that Seam will always return the same instance as far as you stay in the context boundaries (in this case until the conversation ends).
I suggest that you rework your code in order to separate a TQIDay standard class (without #Name and #Inject) to model the data you need to manage and collect in multiple instances, from an TQIActionBean where you can have your EntityManager injected.
Related
i have been programming code for over two decades, but am new to java ee 7.
i have purchased antonio gonclaves book and modified his code to get going, but can't quite get all of the details down to get the data to store in the database for future retrievals.
i simply want to have three strings entered in by the user, and have them listed on the same xhtml page in a datatable using jsf.
the jsf form works, as i can instantly see the results of the submitted form on my page.
the problem is that it seems like the object is not persisting in the database or even that the database is not even being created.
this is evident by the fact that the datatable is not generating new items.
is there any way to monitor the logs, or see what is going on behind the scenes? or, am i simply missing a little detail?
i can show my sections of my code if you ask.
this is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="saciMataPU" transaction-type="JTA">
<jta-data-source>java:global/jdbc/nityanandaDB</jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
as per the antonio gonclaves code from chapter 11 of his book, i created an entity class, a class that interfaces with the xhtml page, and an ejb class.
this is my EJB:
package gaurirasa.bhaktios.globallydevoted;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import java.util.List;
#Named
#Stateless
public class SaciMataEJB {
// ======================================
// = Attributes =
// ======================================
#PersistenceContext(unitName = "saciMataPU")
private EntityManager em;
// ======================================
// = Business methods =
// ======================================
public Kurukshetra createKurukshetra(Kurukshetra kurukshetra) {
em.persist(kurukshetra);
return kurukshetra;
}
public List<Kurukshetra> findAllkurukshetras() {
return em.createNamedQuery("findAllKurukshetras", Kurukshetra.class).getResultList();
}
public Kurukshetra findKurukshetraById(Long id) {
return em.find(Kurukshetra.class, id);
}
}
solved
After the help from Marged, it was eventually clear that all that was needed to be done was to modify the jta-data-source in the persistence.xml file. i was basically under a lack of conceptual understanding of the process of connecting to a glassfish resource.
old jta-data-source:
<jta-data-source>java:global/jdbc/nityanandaDB</jta-data-source>
new jta-data-source:
<jta-data-source>jdbc/__default</jta-data-source>
this modification simply uses the default derby connection pool as its database resource.
also, during the troubleshooting, i went ahead and created a database using the ij command line tool
I am working on an application, to be deployed in WebLogic 12c, which needs to be able to obtain a JPA EntityManager (EclipseLink 2.5.2) connected to an arbitrary Data Source at runtime. I do not currently know what the JNDI name of that Data Source will be; there will be several to many of them, connected to different databases but all with identical schemas. So the data source name cannot be specified in the persistence.xml inside the application; it must come from outside (configuration file most likely).
I don't think I can have an EntityManagerFactory or EntityManager injected; they are pretty tightly coupled to the configuration in persistence.xml and I do not seem to be able to override the JTA data source name. This, for example, does not work:
#PersistenceUnit(unitName="myPU")
private EntityManagerFactory emf;
// ...
Map<String, Object> emProps = new HashMap<String, Object>();
emProps.put(EntityManagerProperties.JTA_DATASOURCE, "jdbc/foobar");
EntityManager em = emf.createEntityManager(emProps);
My as my EntityManager here is still connected to the JTA datasource that was actually specified in the persistence.xml.
So I started looking at creating the EntityMangerFactory through non-injected means, like with Persistence.createEntityManagerFactory(puName, propMap) but here, it seems, no matter what persistence.xml or my property map says, I get a RESOURCE_LOCAL EntityManagerFactory!
How can I get an EntityManager or EntityManagerFactory that is JTA-enabled and associated with an arbitrary datasource name that is not known at compile-time?
This does the trick, at least in EclipseLink 2.5.2:
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "JTA");
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, "jdbc/foobar");
emf = Persistence.createEntityManagerFactory("myPU", properties);
JpaEntityManagerFactory jemf = (JpaEntityManagerFactory)emf;
WebLogicTransactionController wlstx = new WebLogicTransactionController();
if (jemf.getDatabaseSession() != null && jemf.getDatabaseSession().getExternalTransactionController() == null) {
jemf.getDatabaseSession().setExternalTransactionController(wlstx);
}
if (jemf.getServerSession() != null && jemf.getServerSession().getExternalTransactionController() == null) {
jemf.getServerSession().setExternalTransactionController(wlstx);
}
By adding the transaction controller to the EMF, it is once again enlisted with JTA and will respect JTA transactions. My persistence.xml provides a dummy value for the JTA datasource; I override in code and away we go!
NB: Currently getDatabaseSession() and getServerSession() in fact return the exact same object. I could get away with only setting one of these, but this is undocumented and you're better off safely setting both of them, just to be sure.
I'm presently struggling with getting Spring Data JPA Auditing to work, it is presently not setting the fields and doesn't seem to be getting called in any way when working with Entities. In particular any insight into how it hooks into the standard flow of persisting Entities would be helpful.
I'm presently using Spring Data JPA 1.5.0.M1 with Spring 3.2.6 and the basic configuration for the auditing piece is:
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
#EnableJpaRepositories(basePackages = "org.myproject.dao")
#EnableTransactionManagement
public class JpaConfig {
...}
the relevant entity at the moment is marked up with the annotations and the interface while trying to work this out (the annotations would be preferred). I realize this should not be done but I copied and pasted for the moment.
#Entity
public class AutoDraft implements Auditable<Long, Long> {
#SequenceGenerator(name="seq_auto_draft", sequenceName="SEQ_AUTO_DRAFT")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_auto_draft")
#Id
private Long id;
#CreatedDate
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime createdDate;
#LastModifiedDate
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime lastModifiedDate;
In the logs the relevant beans are being set up and I can catch the AuditingHandler being properly configured within the AuditingEntityListener on startup, but nothing seems to be getting triggered at runtime, nor are there any audit related logging messages associated with specific entities or repositories. My attention is presently drawn by the AuditingBeanFactoryPostProcessor, but I've already spent too long on this so could use any assistance.
I know this is an old question, but I hit the same problem and a comment helped me resolve it. So I thought I would make it clearer if anyone falls on this question again.
The documentation for Spring Data is a bit misleading in that it implies that you can enable auditing simply by annotating a #Configuration class with #EnableJpaAuditing.
However, the part I found unclear is that you still need to modify the orm.xml file (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#auditing):
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
However, if you are using a pure annotation based solution, you may not have an orm.xml file. As indicated by Matt Whipple in a comment, you have to add the #EntityListeners annotation to you entity classes so that the JPA persistence library calks the Spring auditing class when persisting the objects (which in turn deals with the auditing).
So a complete example could be something like:
#Configuration
#EnableJpaAuditing
#PropertySource({ "application.properties" })
public class AppConfig {
/**
* Stubbed method for the auditor as the app does not concern itself with auditing any User fields
* Consequently, return null for the current auditor
* #return
*/
#Bean
public AuditorAware<User> auditorProvider(){
return new AuditorAware<User>() {
#Override
public User getCurrentAuditor() {
return <User object that is Logged In>;
}
};
}
}
Then on your entity:
#Entity
#EntityListeners(AuditingEntityListener.class)
public class Log {
#Id
#GeneratedValue
private long id;
#CreatedDate
#Column(nullable=false)
private Date createdOn;
// bunch of other audit fields (and other fields)
...
...
}
It seems like you forgot to configure AuditingEntityListener in the orm.xml (which is still neccessary). Add this lines to your orm.xml:
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
see: Spring data jpa documentation: Auditing.
I try to persist my Department and Mandator classes to hsqhldb but it gives this error.
Exception Description: [class ch.printsoft.mailhouse.usermgr.entity.Mandator] uses a non-entity [class ch.printsoft.mailhouse.usermgr.entity.Department] as target entity in the relationship attribute [field departments].
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:126)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:115)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
These are the classes that I try to persist to my database. I really don't know what the problem is.
#Entity
public class Mandator {
#Id
#GeneratedValue
private Integer id;
private String mandatorId;
#OneToMany(mappedBy = "mandator")
private List<MandatorUser> mandatorUsers;
#OneToMany(mappedBy = "mandator")
private List<SLAFamilyGroup> slaFamilyGroups;
#OneToMany(mappedBy = "mandator")
private List<Group> groups;
#OneToMany(mappedBy = "mandator")
private List<Department> departments;
#OneToMany(mappedBy = "mandator")
private List<CostUnit> costUnits;
#Entity
public class Department {
#Id
#GeneratedValue
private Integer id;
private String name;
private String responsiblePerson;
private String location;
#ManyToOne(optional = false)
private Mandator mandator;
#ManyToMany
private List<DocumentUser> documentUsers;
I've really tried every thing but it didn't work.
I just spent a lot of time debugging a seemingly unexplainable case of this exception, so I'm just leaving my story here.
If you're using a somewhat old implementation of JPA (e.g. EclipseLink 2.5.x) and you're using modern Java 8 features (such as lambda expressions) in your code base - don't ever use them in the JPA entity classes.
EclipseLink 2.5's class metadata parser crashes upon encountering Java 8 features (such as lambda expressions, method references etc.) in the bytecode. The internal crash is a very unfriendly ArrayIndexOutOfBoundsException, but you don't even get to see it, as the weaver code silently ignores metadata parser crashes and just assumes the class has no interesting metadata. This leads it to believe that the class in question is not an entity even though it has all the proper annotations, and the end result is the error message we are talking about.
Bottom line: Don't use Java 8 lambdas in JPA entity classes. EVER.
Ensure you have both classes listed in your persistence.xml, and the both classes are on the classpath.
Please include your persistence.xml.
I hope this can help someone.
I had the same problem.
The night before, everything was ok.
In NetBeans I've checked, using History, all the files involved in the error.
Persistence.xml included.
Nothing was changed.
I've checked also manually.
I've tryed all the solution suggested in this thread even migrate to eclipselink 2.6.4.
I've removed the 2 class involved in the persistence.xml, saved it, and added again.
The error was still there.
Then, I've removed ALL the classess in the list of the Entity Classes included in the persistence.xml, and then I've included them again.
Now it works.
Magically.
But really there were non difference in the history.
Even a single character.
Ensure you have defined both classes are under < persistence-unit > tag of persistence.xml file. As we know At the time of persistence the entity into DB. Our Application finds the entity classes information from persistence.xml file. If entity's mapping is not found in persistence.xml, then application throw this exception while you will perform any operation on that entity like here your are.
So Please make both entities entry in your persistence.xml
Example:
persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="mapping_unit">
<class>ch.printsoft.mailhouse.usermgr.entity.Mandator </class>
<class>ch.printsoft.mailhouse.usermgr.entity.Department</class>
...
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/practice" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="eclipselink.logging.level" value="SEVERE" />
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
</properties>
</persistence-unit>
</persistence>
Remove mappedBy from #OneToMany annotations from Mandator class
Check if all related classes are mapped as #Entity. Department class has #ManyToMany relation to DocumentUser. Provide the listing of DocumentUser class
Make sure that both "class" files are in the same jar.
Make sure that you don't have two .class files with the same name !
Ensure you have both classes has the property of PK and the no parameter constructor.
I add the following code in my entity class.
#Entity
public class EntityClass{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public EntityClass() {
}
...
}
Examine your mappedBy=xxx and make sure xxx is unique in whole project.
1))Proper relationship for the parent and child.
First Class
#Entity
#Table(name="nova_payment_result")
#NamedQuery(name="NovaPaymentResult.findAll", query="SELECT n FROM NovaPaymentResult n")
#JsonIgnoreProperties({"novaOrder"})
public class NovaPaymentResult implements Serializable {
private static final long serialVersionUID = 1L;
//bi-directional many-to-one association to NovaOrder
#JsonIgnoreProperties("paymentResults")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="orderid")
private NovaOrder novaOrder;
2nd class
#Entity
#Table(name="nova_order")
#NamedQueries({
#NamedQuery(name="NovaOrder.findAll", query="SELECT n FROM NovaOrder n")
})
#JsonIgnoreProperties({"novaOrders","novaCustomerProfile"})
public class NovaOrder implements Serializable {
private static final long serialVersionUID = 1L;
#OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="novaOrder")
private List<NovaPaymentResult> paymentResults;
Makesure entery in persistence.xml should be there for both classes.
What a nightmare. For me it worked when I invalidated the caches of IntelliJ Idea from the File menu
Could you please explain to me how to add a standalone c3pO or DBCP connection pool to my toplink-based JPA project?
I have a persistence.xml file, and everytime I want to query the database, I'm doing this:
EntityManagerFactory emf = this.getEntityManagerFactory();
// Surely using persistence.xml to set up the factory
EntityManager em = emf.createEntityManager();
...
Where do I build the bridge between my external connection pool manager and Toplink? Any ideas or links are welcomed.
Regards,
Jean
I don't use Toplink so I didn't test this but, my understanding of various resources found over the net is that you'll need to provide an implementation of SessionCustomizer. In this implementation, use the JNDIConnector class to give a DataSource object (c3p0 implements the DataSource API) using the setDataSource(javax.sql.DataSource) method.
Adapt the sample from Working with a non JTA DataSource in Toplink Essentials.
I really don't understand what to do. So blurry page for a beginner. Nevertheless, I have created a SessionCustomizer class apart. Here is my customize() method, using c3p0:
public void customize(Session session) throws Exception{
DataSource ds = DataSources.unpooledDataSource("myServerURL", "login", "pwd");
DataSource pooled = DataSources.pooledDataSource(ds);
JNDIConnector conn = (JNDIConnector)session.getLogin().getConnector();
conn.setDataSource(pooled);
conn.setLookupType(JNDIConnector.STRING_LOOKUP);
}
I don't even think it's correct. I'm putting my connection infos in clear in code, really weird.
Secondly, in persistence.xml example from the link, they have put:
<non-jta-data-source>java:comp/env/jdbc/DefaultDS</non-jta-data-source>
<class>sample.MyEntity</class>
<properties>
<property name="toplink.session.customizer" value="es.claro.commons.ds.DataSourceSessionCustomizer"/>
</properties>
What should I put in mine, particularly for "non-jta-data-source" tag? Is there a way to put connection informations in that xml instead of in code?
Help.