Search Results

Search found 955 results on 39 pages for 'jpa'.

Page 23/39 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • How to call Named Query

    - by sandeep
    I wrote a named query in the entity class Voter NamedQuery(name = "Voter.findvoter", query = "SELECT count(*) FROM Voter v WHERE v.voterID = :voterID" and where v.password= : password), I want to call this named query and I also need to set voterID and password. Can you help me. Thank you

    Read the article

  • Hibernate annotated many-to-one not adding child to parent Collection

    - by Rob Hruska
    I have the following annotated Hibernate entity classes: @Entity public class Cat { @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) @Id private Long id; @OneToMany(mappedBy = "cat", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<Kitten> kittens = new HashSet<Kitten>(); public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setKittens(Set<Kitten> kittens) { this.kittens = kittens; } public Set<Kitten> getKittens() { return kittens; } } @Entity public class Kitten { @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) @Id private Long id; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Cat cat; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setCat(Cat cat) { this.cat = cat; } public Cat getCat() { return cat; } } My intention here is a bidirectional one-to-many/many-to-one relationship between Cat and Kitten, with Kitten being the "owning side". What I want to happen is when I create a new Cat, followed by a new Kitten referencing the Cat, the Set of kittens on my Cat should contain the new Kitten. However, this does not happen in the following test: @Test public void testAssociations() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); Cat cat = new Cat(); session.save(cat); Kitten kitten = new Kitten(); kitten.setCat(cat); session.save(kitten); tx.commit(); assertNotNull(kitten.getCat()); assertEquals(cat.getId(), kitten.getCat().getId()); assertTrue(cat.getKittens().size() == 1); // <-- ASSERTION FAILS assertEquals(kitten, new ArrayList<Kitten>(cat.getKittens()).get(0)); } Even after re-querying the Cat, the Set is still empty: // added before tx.commit() and assertions cat = (Cat)session.get(Cat.class, cat.getId()); Am I expecting too much from Hibernate here? Or is the burden on me to manage the Collection myself? The (Annotations) documentation doesn't make any indication that I need to create convenience addTo*/removeFrom* methods on my parent object. Can someone please enlighten me on what my expectations should be from Hibernate with this relationship? Or if nothing else, point me to the correct Hibernate documentation that tells me what I should be expecting to happen here. What do I need to do to make the parent Collection automatically contain the child Entity?

    Read the article

  • ORM in the realworld

    - by josh
    I am begining a new project that i think will last for some years. Am in the point of deciding the ORM framework to use (or whether to use one at all). Can anyone with experience tell me whether orm frameworks are used in realworld applications. The problem i have in mind is this: The orm tool will generate for me tables and columns etc as i create and modify my entities. However, after the project has gone live and is in production, certain database changes will not be possible. Can this hinder the advancement of the project. If i had used a framework like ibatis for example, i know i would only need to adjust the sql statements based on the database changes. Can someone tell me whether ORM tools have survived the live environment. At my office, we use java based ERP that was done long ago and it was never done using any ORM framework. Regards. Josh

    Read the article

  • How to handle Oracle Store Procedure call with Oracle Types as input or output using EclipseLink

    - by MAK
    Hi, I doing a Proof Of Concept to figure out how efficient to call a store procedure using EclipseLink. I was able to call oracle store procedure using EclispeLink with Scalar/primitive data types (link Integer, varchar etc). I wanted to understand how can I handle Oracle Store procedure from EclipseLink with collection(Oracle Types/User defined types) as input or output parameters. I would really appreciate if some one help me understand this with an example. Thanks MAK

    Read the article

  • Toplink Exception, whats wrong?

    - by java_dude
    Hey, I've got an excpetion when I generate this EJB SQL Statement. Exception Description: Syntax error parsing the query [SELECT h FROM Busmodul h WHERE LOWER(h.modulNummer) LIKE :modulnummer AND h.einbauort.id = :einbauort_fk AND h.plattform.id = :plattform_fk ORDER BY TRIM(TRAILING '-' FROM CONCAT('0', h.modulNummer))], line 1, column 150: syntax error at [TRIM]. Internal Exception: line 1:150: expecting IDENT, found 'TRIM' Whats the meaning of IDENT. Any Ideas what I am doing wrong? Regards

    Read the article

  • How do i write this jpql query?

    - by Nitesh Panchal
    Hello, Say i have 5 tables, tblBlogs tblBlogPosts tblBlogPostComment tblUser tblBlogMember BlogId BlogPostsId BlogPostCommentId UserId BlogMemberId BlogTitle BlogId CommentText FirstName UserId PostTitle BlogPostsId BlogId BlogMemberId Now i want to retrieve only those blogs and posts for which blogMember has actually commented. So in short, how do i write this plain old sql :- Select b.BlogTitle, bp.PostTitle, bpc.CommentText from tblBlogs b Inner join tblBlogPosts bp on b.BlogId = bp.BlogId Inner Join tblBlogPostComment bpc on bp.BlogPostsId = bpc.BlogPostsId Inner Join tblBlogMember bm On bpc.BlogMemberId = bm.BlogMemberId Where bm.UserId = 1; As you can see, everything is Inner join, so only that row will be retrieved for which the user has commented on some post of some blog. So, suppose he has joined 3 blogs whose ids are 1,2,3 (The blogs which user has joined are in tblBlogMembers) but the user has only commented in blog 2 (of say BlogPostId = 1). So that row will be retrieved and 1,3 won't as it is Inner Join. How do i write this kind of query in jpql? In jpql, we can only write simple queries like say :- Select bm.blogId from tblBlogMember Where bm.UserId = objUser; Where objUser is supplied using :- em.find(User.class,1); Thus once we get all blogs(Here blogId represents a blog object) which user has joined, we can loop through and do all fancy things. But i don't want to fall in this looping business and write all this things in my java code. Instead, i want to leave that for database engine to do. So, how do i write the above plain sql into jpql? and what type of object the jpql query will return? because i am only selecting few fields from all table. In which class should i typecast the result to? I think i posted my requirement correctly, if i am not clear please let me know. Thanks in advance :).

    Read the article

  • Best Persistence API for use with GWT

    - by KevMo
    What is the best persistence API for use with GWT? Sadly, the application will be hosted on my own java server, as I will need more control than GAE will give me. I know I will need to have two sets of my entities, one for the server side, and some pojo's for the client side. I'm looking to make the mapping of the data as simple as possible between the two, but these will be deeply nested objects so it has to be robust. I was looking at Dozer for my mapping needs. Previously I've used EJB3 with TopLink, so that's very familiar to me, but I would like to get community input on what other API's work well with Dozer and GWT.

    Read the article

  • Regarding Toplink Fetching Policy

    - by Chandu
    Hi, I'm working for a Swing Project and the technologies used are netbeans with Toplink essentials, mysql. The Problem I'm facing is the entity object dosn't get updated after insertions take place while calling a getter collection of the foreign key property. Ex: I have 2 tables Table1,Table2. I have sno column, id column as a primary key in Table1 & is Foreign Key in Table2. Through find method I just get the particular sno object(existed in table 1) set some values persisted to table2 & committed the transaction. When I select the same sno object through find method & gets its collection from Table2 through the getTable2Collection() of the bean(as it is already created in bean by toplink essential) I'm unable to get the latest added record except that all other records of it are displayed. After I close the application & opening it then the new record gets reflected while calling the same sno through the above process. I came to know that this is a kind of lazy fetching and there should be some way of fetch policy to be changed to make the entity object get updated with the changes. So Please help me in this regard. Regards, Chandu

    Read the article

  • EntityManager injection works in JBoss 7.1.1 but not WebSphere 7

    - by BikerJared
    I've built an EJB that will manage my database access. I'm building a web app around it that uses Struts 2. The problem I'm having is when I deploy the ear, the EntityManager doesn't get injected into my service class (and winds up null and results in NullPointerExceptions). The weird thing is, it works on JBoss 7.1.1 but not on WebSphere 7. You'll notice that Struts doesn't inject the EJB, so I've got some intercepter code that does that. My current working theory right now is that the WS7 container can't inject the EntityManager because of Struts for some unknown reason. My next step is to try Spring next, but I'd really like to get this to work if possible. I've spent a few days searching and trying various things and haven't had any luck. I figured I'd give this a shot. Let me know if I can provide additional information. <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="JPATestPU" transaction-type="JTA"> <description>JPATest Persistence Unit</description> <jta-data-source>jdbc/Test-DS</jta-data-source> <class>org.jaredstevens.jpatest.db.entities.User</class> <properties> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence> package org.jaredstevens.jpatest.db.entities; import java.io.Serializable; import javax.persistence.*; @Entity @Table public class User implements Serializable { private static final long serialVersionUID = -2643583108587251245L; private long id; private String name; private String email; @Id @GeneratedValue(strategy = GenerationType.TABLE) public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(nullable=false) public String getName() { return this.name; } public void setName( String name ) { this.name = name; } @Column(nullable=false) public String getEmail() { return this.email; } @Column(nullable=false) public void setEmail( String email ) { this.email= email; } } package org.jaredstevens.jpatest.db.services; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.Query; import org.jaredstevens.jpatest.db.entities.User; import org.jaredstevens.jpatest.db.interfaces.IUserService; @Stateless(name="UserService",mappedName="UserService") @Remote public class UserService implements IUserService { @PersistenceContext(unitName="JPATestPU",type=PersistenceContextType.TRANSACTION) private EntityManager em; @TransactionAttribute(TransactionAttributeType.REQUIRED) public User getUserById(long userId) { User retVal = null; if(userId > 0) { retVal = (User)this.getEm().find(User.class, userId); } return retVal; } @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<User> getUsers() { List<User> retVal = null; String sql; sql = "SELECT u FROM User u ORDER BY u.id ASC"; Query q = this.getEm().createQuery(sql); retVal = (List<User>)q.getResultList(); return retVal; } @TransactionAttribute(TransactionAttributeType.REQUIRED) public void save(User user) { this.getEm().persist(user); } @TransactionAttribute(TransactionAttributeType.REQUIRED) public boolean remove(long userId) { boolean retVal = false; if(userId > 0) { User user = null; user = (User)this.getEm().find(User.class, userId); if(user != null) this.getEm().remove(user); if(this.getEm().find(User.class, userId) == null) retVal = true; } return retVal; } public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } } package org.jaredstevens.jpatest.actions.user; import javax.ejb.EJB; import org.jaredstevens.jpatest.db.entities.User; import org.jaredstevens.jpatest.db.interfaces.IUserService; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { @EJB(mappedName="UserService") private IUserService userService; private static final long serialVersionUID = 1L; private String userId; private String name; private String email; private User user; public String getUserById() { String retVal = ActionSupport.SUCCESS; this.setUser(userService.getUserById(Long.parseLong(this.userId))); return retVal; } public String save() { String retVal = ActionSupport.SUCCESS; User user = new User(); if(this.getUserId() != null && Long.parseLong(this.getUserId()) > 0) user.setId(Long.parseLong(this.getUserId())); user.setName(this.getName()); user.setEmail(this.getEmail()); userService.save(user); this.setUser(user); return retVal; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return this.name; } public void setName( String name ) { this.name = name; } public String getEmail() { return this.email; } public void setEmail( String email ) { this.email = email; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } } package org.jaredstevens.jpatest.utils; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class EJBAnnotationProcessorInterceptor implements Interceptor { private static final long serialVersionUID = 1L; public void destroy() { } public void init() { } public String intercept(ActionInvocation ai) throws Exception { EJBAnnotationProcessor.process(ai.getAction()); return ai.invoke(); } } package org.jaredstevens.jpatest.utils; import java.lang.reflect.Field; import javax.ejb.EJB; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBAnnotationProcessor { public static void process(Object instance)throws Exception{ Field[] fields = instance.getClass().getDeclaredFields(); if(fields != null && fields.length > 0){ EJB ejb; for(Field field : fields){ ejb = field.getAnnotation(EJB.class); if(ejb != null){ field.setAccessible(true); field.set(instance, EJBAnnotationProcessor.getEJB(ejb.mappedName())); } } } } private static Object getEJB(String mappedName) { Object retVal = null; String path = ""; Context cxt = null; String[] paths = {"cell/nodes/virgoNode01/servers/server1/","java:module/"}; for( int i=0; i < paths.length; ++i ) { try { path = paths[i]+mappedName; cxt = new InitialContext(); retVal = cxt.lookup(path); if(retVal != null) break; } catch (NamingException e) { retVal = null; } } return retVal; } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="basicstruts2" namespace="/diagnostics" extends="struts-default"> <interceptors> <interceptor name="ejbAnnotationProcessor" class="org.jaredstevens.jpatest.utils.EJBAnnotationProcessorInterceptor"/> <interceptor-stack name="baseStack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="ejbAnnotationProcessor"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="baseStack"/> </package> <package name="restAPI" namespace="/conduit" extends="json-default"> <interceptors> <interceptor name="ejbAnnotationProcessor" class="org.jaredstevens.jpatest.utils.EJBAnnotationProcessorInterceptor" /> <interceptor-stack name="baseStack"> <interceptor-ref name="defaultStack" /> <interceptor-ref name="ejbAnnotationProcessor" /> </interceptor-stack> </interceptors> <default-interceptor-ref name="baseStack" /> <action name="UserAction.getUserById" class="org.jaredstevens.jpatest.actions.user.UserAction" method="getUserById"> <result type="json"> <param name="ignoreHierarchy">false</param> <param name="includeProperties"> ^user\.id, ^user\.name, ^user\.email </param> </result> <result name="error" type="json" /> </action> <action name="UserAction.save" class="org.jaredstevens.jpatest.actions.user.UserAction" method="save"> <result type="json"> <param name="ignoreHierarchy">false</param> <param name="includeProperties"> ^user\.id, ^user\.name, ^user\.email </param> </result> <result name="error" type="json" /> </action> </package> </struts> Stack Trace java.lang.NullPointerException org.jaredstevens.jpatest.actions.user.UserAction.save(UserAction.java:38) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) java.lang.reflect.Method.invoke(Method.java:611) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255) org.jaredstevens.jpatest.utils.EJBAnnotationProcessorInterceptor.intercept(EJBAnnotationProcessorInterceptor.java:21) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:188) com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:116) com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:77) com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908) com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:997) com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.invokeFilters(DefaultExtensionProcessor.java:1062) com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest(DefaultExtensionProcessor.java:982) com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3935) com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276) com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931) com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583) com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:276) com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214) com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113) com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165) com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775) com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1604)

    Read the article

  • How to manage a One-To-One and a One-To-Many of same type as unidirectional mapping?

    - by user1652438
    I'm trying to implement a model for private messages between two or more users. That means I've got two Entities: User PrivateMessage The User model shouldn't be edited, so I'm trying to set up an unidirectional relationship: @Entity (name = "User") @Table (name = "user") public class User implements Serializable { @Id String username; String password; // something like this ... } The PrivateMessage Model addresses multiple receivers and has exactly one sender. So I need something like this: @Entity (name = "PrivateMessage") @Table (name = "privateMessage") @XmlRootElement @XmlType (propOrder = {"id", "sender", "receivers", "title", "text", "date", "read"}) public class PrivateMessage implements Serializable { private static final long serialVersionUID = -9126766942868177246L; @Id @GeneratedValue private Long id; @NotNull private String title; @NotNull private String text; @NotNull @Temporal(TemporalType.TIMESTAMP) private Date date; @NotNull private boolean read; @NotNull @ElementCollection(fetch = FetchType.EAGER, targetClass = User.class) private Set<User> receivers; @NotNull @OneToOne private User sender; // and so on } The according 'privateMessage' table won't be generated and just the relationship between the PM and the many receivers is satisfied. I'm confused about this. Everytime I try to set a 'mappedBy' attribute, my IDE marks it as an error. It seems to be a problem that the User-entity isn't aware of the private message which maps it. What am I doing wrong here? I've solved some situation similar to this one, but none of those solutions will work here. Thanks in advance!

    Read the article

  • Hibernate, EHCache, Read-Write cache, adding item to a list

    - by Walter White
    Hi all, I have an entity that has a collection in it. The collection is a OneToMany unidirectional relationship storing who viewed a particular file. The problem I am having is that after I load the entity and try to update the collection, I don't get any errors, but the collection is never updated: Entity: @OneToMany(cascade = CascadeType.PERSIST) @JoinTable protected List<User> users; File Servlet @In private EntityQuery<File> File_findById; ... File file = File_findById(fileId); file.getUsers().add(user); session.update(file); Even though I call session.update(file) and I see stuff in hibernate logs, I don't see anything in the database indicating that it was saved. Walter

    Read the article

  • Foreign Key constraint violation when persisting a many-to-one class

    - by tieTYT
    I'm getting an error when trying to persist a many to one entity: Internal Exception: org.postgresql.util.PSQLException: ERROR: insert or update on table "concept" violates foreign key constraint "concept_concept_class_fk" Detail: Key (concept_class_id)=(Concept) is not present in table "concept_class". Error Code: 0 Call: INSERT INTO concept (concept_key, description, label, code, concept_class_id) VALUES (?, ?, ?, ?, ?) bind = [27, description_1, label_1, code_1, Concept] Query: InsertObjectQuery(com.mirth.results.entities.Concept[conceptKey=27]) at com.sun.ejb.containers.BaseContainer.checkExceptionClientTx(BaseContainer.java:3728) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:3576) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1354) ... 101 more Here is the method that tries to persist it. I've put a comment where the line is: @Override public void loadConcept(String metaDataFilePath, String dataFilePath) throws Exception { try { ConceptClassMetaData conceptClassMetaData = (ConceptClassMetaData) ModelSerializer.getInstance().fromXML(FileUtils.readFileToString(new File(metaDataFilePath), "UTF8")); em.executeNativeQuery(conceptClassMetaData.getCreateStatement()); ConceptClassRow conceptClassRow = conceptClassMetaData.getConceptClassRow(); ConceptClass conceptClass = em.findByPrimaryKey(ConceptClass.class, conceptClassRow.getId()); if (conceptClass == null) { conceptClass = new ConceptClass(conceptClassRow.getId()); } conceptClass.setLabel(conceptClassRow.getLabel()); conceptClass.setOid(conceptClassRow.getOid()); conceptClass.setDescription(conceptClassRow.getDescription()); conceptClass = em.merge(conceptClass); DataParser dataParser = new DataParser(conceptClassMetaData, dataFilePath); for (ConceptModel conceptModel : dataParser.getConceptRows()) { ConceptFilter<Concept> filter = new ConceptFilter<Concept>(Concept.class); filter.setCode(conceptModel.getCode()); filter.setConceptClass(conceptClass.getLabel()); List<Concept> concepts = em.findAllByFilter(filter); Concept concept = new Concept(); if (concepts != null && !concepts.isEmpty()) { concept = concepts.get(0); } concept.setCode(conceptModel.getCode()); concept.setDescription(conceptModel.getDescription()); concept.setLabel(conceptModel.getLabel()); concept.setConceptClass(conceptClass); concept = em.merge(concept); //THIS LINE CAUSES THE ERROR! } } catch (Exception e) { e.printStackTrace(); throw e; } } ... Here are how the two entities are defined: @Entity @Table(name = "concept") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="concept_class_id", discriminatorType=DiscriminatorType.STRING) public class Concept extends KanaEntity { @Id @Basic(optional = false) @Column(name = "concept_key") protected Integer conceptKey; @Basic(optional = false) @Column(name = "code") private String code; @Basic(optional = false) @Column(name = "label") private String label; @Column(name = "description") private String description; @JoinColumn(name = "concept_class_id", referencedColumnName = "id") @ManyToOne private ConceptClass conceptClass; ... @Entity @Table(name = "concept_class") public class ConceptClass extends KanaEntity { @Id @Basic(optional = false) @Column(name = "id") private String id; @Basic(optional = false) @Column(name = "label") private String label; @Column(name = "oid") private String oid; @Column(name = "description") private String description; .... And also, what's important is the sql that's being generated: INSERT INTO concept_class (id, oid, description, label) VALUES (?, ?, ?, ?) bind = [LOINC_TEST, 2.16.212.31.231.54, This is a meta data file for LOINC_TEST, loinc_test] INSERT INTO concept (concept_key, description, label, code, concept_class_id) VALUES (?, ?, ?, ?, ?) bind = [27, description_1, label_1, code_1, Concept] The reason this is failing is obvious: It's inserting the word Concept for the concept_class_id. It should be inserting the word LOINC_TEST. I can't figure out why it's using this word. I've used the debugger to look at the Concept and the ConceptClass instance and neither of them contain this word. I'm using eclipselink. Does anyone know why this is happening?

    Read the article

  • Which Web2.0 framework does integrate with JPA2 best?

    - by erlord
    Hi all My choice is between Tapestry 5 Vaadin JSF2 I like Vaadin most, because it seems to come with all the look-and-feel features out-of-the-box, I wonder if anyone has experience with Vaadin and JPA2, preferrably EclipseLink. JPA2 is absolutely essential, the Web2.0 framework must integrate with it. Thanks Err

    Read the article

  • how openjpa2.0 enhances entities at runtime?

    - by Digambar Daund
    Below is my test code: package jee.jpa2; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test public class Tester { EntityManager em; EntityTransaction tx; EntityManagerFactory emf; @BeforeClass public void setup() { emf = Persistence.createEntityManagerFactory("basicPU", System.getProperties()); } @Test public void insert() { Item item = new Item(); for (int i = 0; i < 1000; ++i) { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); item.setId(null); em.persist(item); tx.commit(); em.clear(); em.close(); tx=null; em=null; } } @Test public void read() { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query findAll = em.createNamedQuery("findAll"); List<Item> all = findAll.getResultList(); for (Item item : all) { System.out.println(item); } tx.commit(); } } And here is the entity: package jee.jpa2; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; @Entity @NamedQuery(name="findAll", query="SELECT i FROM Item i") public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", nullable = false, updatable= false) protected Long id; protected String name; public Item() { name = "Digambar"; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return String.format("Item [id=%s, name=%s]", id, name); } } After executing test I get Error: Item [id=1, name=Digambar] Item [id=2, name=Digambar] PASSED: read FAILED: insert <openjpa-2.0.0-r422266:935683 nonfatal store error> org.apache.openjpa.persistence.EntityExistsException: Attempt to persist detached object "jee.jpa2.Item-2". If this is a new instance, make sure any version and/or auto-generated primary key fields are null/default when persisting. FailedObject: jee.jpa2.Item-2 at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2563) at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2423) at org.apache.openjpa.kernel.DelegatingBroker.persist(DelegatingBroker.java:1069) at org.apache.openjpa.persistence.EntityManagerImpl.persist(EntityManagerImpl.java:705) at jee.jpa2.Tester.insert(Tester.java:33) Please Explain whats happening here?

    Read the article

  • hibernate query cache specify cache duration

    - by cometta
    below is how i do query cache getHibernateTemplate().setCacheQueries(true); List<IssSection> result = (List<IssSection>) getHibernateTemplate().findByCriteria(crit); getHibernateTemplate().setCacheQueries(false); may i know how to specify duration of maximum time to cache this method? let say i want to clear cache after 5 mins expirated

    Read the article

  • In Seam what's the difference between injected EntityManager and getEntityManager from EntityHome

    - by Navi
    I am testing a Seam application using the needle test API. In my code I am using the getEntityManager() method from EntityHome. When I run the unit tests against an in memory database I get the following exception: java.lang.IllegalStateException: No application context active at org.jboss.seam.Component.forName(Component.java:1945) at org.jboss.seam.Component.getInstance(Component.java:2005) at org.jboss.seam.Component.getInstance(Component.java:1983) at org.jboss.seam.Component.getInstance(Component.java:1977) at org.jboss.seam.Component.getInstance(Component.java:1972) at org.jboss.seam.framework.Controller.getComponentInstance(Controller.java:272) at org.jboss.seam.framework.PersistenceController.getPersistenceContext(PersistenceController.java:20) at org.jboss.seam.framework.EntityHome.getEntityManager(EntityHome.java:177) etc .. I can resolve some of these errors by injecting the EntityManager with @In EntityManager entityManager; Unfortunately the persist method of EntityHome also calls the getEntityManager. This means a lot of mocks or rewriting the code somehow. Is there any workaround and why is this exception thrown anyway? I am using Seam 2.2.0 GA by the way. There is nothing special about the components. They are generated by seam-gen. The test is performed with in memory database - I followed the examples in http://jbosscc-needle.sourceforge.net/jbosscc-needle/1.0/db-util.html.

    Read the article

  • Result set mapping in Grails / GORM

    - by armandino
    I want to map the result of a native SQL query to a simple bean in grails, similar to what the @SqlResultSetMapping annotation does. For example, given a query select x.foo, y.bar, z.baz from //etc... map the result to class FooBarBaz { String foo String bar String baz } Can anyone provide an example of how to do this in grails? Thanks in advance.

    Read the article

  • Foreign Key constraint when persisting a many-to-one class

    - by tieTYT
    I'm getting an error when trying to persist a many to one entity: Internal Exception: org.postgresql.util.PSQLException: ERROR: insert or update on table "concept" violates foreign key constraint "concept_concept_class_fk" Detail: Key (concept_class_id)=(Concept) is not present in table "concept_class". Error Code: 0 Call: INSERT INTO concept (concept_key, description, label, code, concept_class_id) VALUES (?, ?, ?, ?, ?) bind = [27, description_1, label_1, code_1, Concept] Query: InsertObjectQuery(com.mirth.results.entities.Concept[conceptKey=27]) at com.sun.ejb.containers.BaseContainer.checkExceptionClientTx(BaseContainer.java:3728) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:3576) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1354) ... 101 more Here is the method that tries to persist it. I've put a comment where the line is: @Override public void loadConcept(String metaDataFilePath, String dataFilePath) throws Exception { try { ConceptClassMetaData conceptClassMetaData = (ConceptClassMetaData) ModelSerializer.getInstance().fromXML(FileUtils.readFileToString(new File(metaDataFilePath), "UTF8")); em.executeNativeQuery(conceptClassMetaData.getCreateStatement()); ConceptClassRow conceptClassRow = conceptClassMetaData.getConceptClassRow(); ConceptClass conceptClass = em.findByPrimaryKey(ConceptClass.class, conceptClassRow.getId()); if (conceptClass == null) { conceptClass = new ConceptClass(conceptClassRow.getId()); } conceptClass.setLabel(conceptClassRow.getLabel()); conceptClass.setOid(conceptClassRow.getOid()); conceptClass.setDescription(conceptClassRow.getDescription()); conceptClass = em.merge(conceptClass); DataParser dataParser = new DataParser(conceptClassMetaData, dataFilePath); for (ConceptModel conceptModel : dataParser.getConceptRows()) { ConceptFilter<Concept> filter = new ConceptFilter<Concept>(Concept.class); filter.setCode(conceptModel.getCode()); filter.setConceptClass(conceptClass.getLabel()); List<Concept> concepts = em.findAllByFilter(filter); Concept concept = new Concept(); if (concepts != null && !concepts.isEmpty()) { concept = concepts.get(0); } concept.setCode(conceptModel.getCode()); concept.setDescription(conceptModel.getDescription()); concept.setLabel(conceptModel.getLabel()); concept.setConceptClass(conceptClass); concept = em.merge(concept); //THIS LINE CAUSES THE ERROR! } } catch (Exception e) { e.printStackTrace(); throw e; } } ... Here are how the two entities are defined: @Entity @Table(name = "concept") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="concept_class_id", discriminatorType=DiscriminatorType.STRING) public class Concept extends KanaEntity { @Id @Basic(optional = false) @Column(name = "concept_key") protected Integer conceptKey; @Basic(optional = false) @Column(name = "code") private String code; @Basic(optional = false) @Column(name = "label") private String label; @Column(name = "description") private String description; @JoinColumn(name = "concept_class_id", referencedColumnName = "id") @ManyToOne private ConceptClass conceptClass; ... @Entity @Table(name = "concept_class") public class ConceptClass extends KanaEntity { @Id @Basic(optional = false) @Column(name = "id") private String id; @Basic(optional = false) @Column(name = "label") private String label; @Column(name = "oid") private String oid; @Column(name = "description") private String description; .... And also, what's important is the sql that's being generated: INSERT INTO concept_class (id, oid, description, label) VALUES (?, ?, ?, ?) bind = [LOINC_TEST, 2.16.212.31.231.54, This is a meta data file for LOINC_TEST, loinc_test] INSERT INTO concept (concept_key, description, label, code, concept_class_id) VALUES (?, ?, ?, ?, ?) bind = [27, description_1, label_1, code_1, Concept] The reason this is failing is obvious: It's inserting the word Concept for the concept_class_id. It should be inserting the word LOINC_TEST. I can't figure out why it's using this word. I've used the debugger to look at the Concept and the ConceptClass instance and neither of them contain this word. I'm using eclipselink. Does anyone know why this is happening?

    Read the article

  • org.hibernate.hql.ast.QuerySyntaxException: TABLE NAME is not mapped

    - by Coronatus
    I have two models, Item and ShopSection. They have a many-to-many relationship. @Entity(name = "item") public class Item extends Model { @ManyToMany(cascade = CascadeType.PERSIST) public Set<ShopSection> sections; } @Entity(name = "shop_section") public class ShopSection extends Model { public List<Item> findActiveItems(int page, int length) { return Item.find("select distinct i from Item i join i.sections as s where s.id = ?", id).fetch(page, length); } } findActiveItems is meant to find items in a section, but I get this error: org.hibernate.hql.ast.QuerySyntaxException: Item is not mapped [select distinct i from Item i join i.sections as s where s.id = ?] at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180) at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111) at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93) at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:322) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3441) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3325) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:733) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:584) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:244) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770) at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:272) ... 8 more What am I doing wrong?

    Read the article

  • Can't create EntityManager

    - by bovo
    New to EJB3, please help/explain. Inside a session bean I declare an EntityManager as follow @PersistenceContext(unitName="ScheduleUnit") private EntityManager em; and this works. But when I do this private EntityManager em; private EntityManagerFactory emf; public void myFunction() { emf = Persistence.createEntityManagerFactory("ScheduleUnit"); em = emf.createEntityManager(); } I get the following error: A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property

    Read the article

  • em.persist seems doesn't persist data on postgreSQL db

    - by Mario
    I've got a simple java main which must write bean data on a PostgreSQL database. I use Entity manager to persist or update object. I use hibernate and toplink driver connection which are specified in persistence.xml file. When I call em.persist(obj), nothing is saved on database, I don't know why. here is my simple code: private static void importa(FileReader f) throws IOException { EntityManagerFactory emf = Persistence .createEntityManagerFactory("orpt2"); EntityManager em = emf.createEntityManager(); dispositivoMedico = new DispositivoMedico(); dispositivoMedico.setCategoria("prova"); dispositivoMedico.setCodice("323"); em.persist(dispositivoMedico); And here is my persistence.xml http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" it.ariadne.orpt2.entities.AccessoriScheda it.ariadne.orpt2.entities.CampiSchede it.ariadne.orpt2.entities.CampiSchedeSalvati it.ariadne.orpt2.entities.CampoAggiuntivo it.ariadne.orpt2.entities.Categorie it.ariadne.orpt2.entities.CategorieCampi it.ariadne.orpt2.entities.CategorieCampiPK it.ariadne.orpt2.entities.ClasseCivab it.ariadne.orpt2.entities.DecodificaStato it.ariadne.orpt2.entities.DispositivoMedico it.ariadne.orpt2.entities.Ente it.ariadne.orpt2.entities.FormaNegoziazione it.ariadne.orpt2.entities.Fornitore it.ariadne.orpt2.entities.LogSession it.ariadne.orpt2.entities.Modello it.ariadne.orpt2.entities.Periodicita it.ariadne.orpt2.entities.Produttore it.ariadne.orpt2.entities.Ruolo it.ariadne.orpt2.entities.RuoloPK it.ariadne.orpt2.entities.RuoloUtente it.ariadne.orpt2.entities.Scheda it.ariadne.orpt2.entities.SchedaSalvata it.ariadne.orpt2.entities.Tipologia it.ariadne.orpt2.entities.Utente Thank you for your help. Mario

    Read the article

  • One entityManger finds entity , the other does not.

    - by Pitelk
    Hi all, I have a very strange behavior in my program. I have 2 classes (class LogIn and CreateGame) where i have injected an EntityManager in each using the annotation @PersistenceContext(unitName="myUnitPU") EntityManager entitymanger; In some point i remove an object called "user" from the database using entitymanger.remove(user) from a method in LogIn class. The business logic is that a user can host and join games ( in the same time) so removing the user all the entries in database about the games the user has created are removed and all the entries showing in which games the user has joined are removed also. After that, i call another function which checks if the user exists using a method in the LogIn class entitymanager.find(user) which surprisingly enough, finds the user. After that I call a method in CreateGame class which tries to find the user by using again entitymanger.find(user) the entitymanger in that class fails to find the user (which is the expected result as the user is removed and it's not in the database) So the question is : Why the entitymanager in one class finds the user (which is wrong) where the other doesn't find it? Does anyone has ever the same problem? PS : This "bug" occurs when the user has hosted a game which is joined by another user (lets call him Buser) and the Buser has made a game which is joined by the current user. GAME | HOST | CLIENTS game1 | user | userB game2 | userB | user where in this case by removing the user, the game1 is deleted and the user is removed from game2 so the result is GAME | HOST | CLIENTS game2 | userB | PS2 : The Beans are EJB3.0. The methods are called from a delegate class. The beans in the delegate class are instantiated using the InitialContext.lookup() method. Note that for logging in ,creating , joining games the appropriate delegate class calls the correspondent EJB which does the transactions. In the case of logOut, the delegate calls an EJB to logout the user but becuase other stuff must be done (as said above) this EJB calls other EJB (again using lookup() ) which has methods like removegame(), removeUserFromGame() etc. After those methods are executed the user is then logged out. Maybe it has something to do with the fact the the first entity manager is called by a delegate but the second from inside an EJb and thats why the one entitymanger can see the non-existent user while the other cannot? Also all the methods have TRANSACTIONTYPE.REQUIRED Thank you in advance

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >