Search Results

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

Page 14/39 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How to handle large dataset with JPA (or at least with Hibernate)?

    - by Roman
    I need to make my web-app work with really huge datasets. At the moment I get either OutOfMemoryException or output which is being generated 1-2 minutes. Let's put it simple and suppose that we have 2 tables in DB: Worker and WorkLog with about 1000 rows in the first one and 10 000 000 rows in the second one. Latter table has several fields including 'workerId' and 'hoursWorked' fields among others. What we need is: count total hours worked by each user; list of work periods for each user. The most straightforward approach (IMO) for each task in plain SQL is: 1) select Worker.name, sum(hoursWorked) from Worker, WorkLog where Worker.id = WorkLog.workerId group by Worker.name; //results of this query should be transformed to Multimap<Worker, Long> 2) select Worker.name, WorkLog.start, WorkLog.hoursWorked from Worker, WorkLog where Worker.id = WorkLog.workerId; //results of this query should be transformed to Multimap<Worker, Period> //if it was JDBC then it would be vitally //to set resultSet.setFetchSize (someSmallNumber), ~100 So, I have two questions: how to implement each of my approaches with JPA (or at least with Hibernate); how would you handle this problem (with JPA or Hibernate of course)?

    Read the article

  • How to use Hibernate SchemaUpdate class with a JPA persistence.xml?

    - by John Rizzo
    I've a main method using SchemaUpdate to display at the console what tables to alter/create and it works fine in my Hibernate project: public static void main(String[] args) throws IOException { //first we prepare the configuration Properties hibProps = new Properties(); hibProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jbbconfigs.properties")); Configuration cfg = new AnnotationConfiguration(); cfg.configure("/hibernate.cfg.xml").addProperties(hibProps); //We create the SchemaUpdate thanks to the configs SchemaUpdate schemaUpdate = new SchemaUpdate(cfg); //The update is executed in script mode only schemaUpdate.execute(true, false); ... I'd like to reuse this code in a JPA project, having no hibernate.cfg.xml file (and no .properties file), but a persistence.xml file (autodetected in the META-INF directory as specified by the JPA spec). I tried this too simple adaptation, Configuration cfg = new AnnotationConfiguration(); cfg.configure(); but it failed with that exception. Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found Has anybody done that? Thanks.

    Read the article

  • Why won't JPA delete owned entities when the owner entity loses the reference to them?

    - by Nick
    Hi! I've got a JPA entity "Request", that owns a List of Answers (also JPA entities). Here's how it's defined in Request.java: @OneToMany(cascade= CascadeType.ALL, mappedBy="request") private List<Answer> answerList; And in Answer.java: @JoinColumn(name = "request", referencedColumnName="id") @ManyToOne(optional = false) private Request request; In the course of program execution, the Request's List of Answers may have Answers added or removed from it, or the actual List object may be replaced. My problem is thus: when I merge a Request to the database, the Answer objects that used to be in the List are kept in the database -- that is, Answer objects that the Request no longer holds a reference to (indirectly, via a List) are not deleted. This is not the behaviour I desire, as if I merge a Request to the database, and then fetch it again, its Answers List may not be the same. Am I making some programming mistake? Is there an annotaion or setting that will ensure that the Answers in the database are exactly the Answers in the Request's List? A solution is to keep references to the original Answers List and then use the EntityManager to remove each old Answer before merging the Request, but it seems like there should be a cleaner way. Thank you!

    Read the article

  • Using the JPA Criteria API, can you do a fetch join that results in only one join?

    - by Shaun
    Using JPA 2.0. It seems that by default (no explicit fetch), @OneToOne(fetch = FetchType.EAGER) fields are fetched in 1 + N queries, where N is the number of results containing an Entity that defines the relationship to a distinct related entity. Using the Criteria API, I might try to avoid that as follows: CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<MyEntity> query = builder.createQuery(MyEntity.class); Root<MyEntity> root = query.from(MyEntity.class); Join<MyEntity, RelatedEntity> join = root.join("relatedEntity"); root.fetch("relatedEntity"); query.select(root).where(builder.equals(join.get("id"), 3)); The above should ideally be equivalent to the following: SELECT m FROM MyEntity m JOIN FETCH myEntity.relatedEntity r WHERE r.id = 3 However, the criteria query results in the root table needlessly being joined to the related entity table twice; once for the fetch, and once for the where predicate. The resulting SQL looks something like this: SELECT myentity.id, myentity.attribute, relatedentity2.id, relatedentity2.attribute FROM my_entity myentity INNER JOIN related_entity relatedentity1 ON myentity.related_id = relatedentity1.id INNER JOIN related_entity relatedentity2 ON myentity.related_id = relatedentity2.id WHERE relatedentity1.id = 3 Alas, if I only do the fetch, then I don't have an expression to use in the where clause. Am I missing something, or is this a limitation of the Criteria API? If it's the latter, is this being remedied in JPA 2.1 or are there any vendor-specific enhancements? Otherwise, it seems better to just give up compile-time type checking (I realize my example doesn't use the metamodel) and use dynamic JPQL TypedQueries.

    Read the article

  • Why does JPA require a no-arg constructor for domain objects ?

    - by Jacques René Mesrine
    Why does JPA require a no-arg constructor for domain objects ? I am using eclipselink and just got this exception during deployment. Exception [EclipseLink-63] (Eclipse Persistence Services-1.1.0.r3639-SNAPSHOT): org.eclipse.persistence.exceptions.DescriptorException Exception Description: The instance creation method [com.me.model.UserVO.<Default Constructor>], with no parameters, does not exist, or is not accessible. Internal Exception: java.lang.NoSuchMethodException: com.me.model.UserVO.<init>() Descriptor: RelationalDescriptor(com.me.model.UserVO --> [DatabaseTable(user)])

    Read the article

  • JPA Is there a way to do something like SELECT <field>, count(*) FROM <table> GROUP BY <field>

    - by javydreamercsw
    I've been looking in the web for examples on the aggregates like count but it seems all of them are using the aggregate alone. SELECT field, count(*) FROM table GROUP BY field Should have something like: field.value1, x1 field.value2, x2 .... I'm looking for a pure JPA answer for this one. If not I guess I can then do further queries just for the count part but that seems unefficient. Any ideas?

    Read the article

  • JPA: what is the proper pattern for iterating over large result sets?

    - by Caffeine Coma
    Let's say I have a table with millions of rows. Using JPA, what's the proper way to iterate over a query against that table, such that I don't have all an in-memory List with millions of objects? I suspect that the following will blow up if the table is large: List<Model> models = entityManager().createQuery("from Model m", Model.class).getResultList(); for (Model model : models) { // do something with model } Is pagination (looping and manually updating setFirstResult()/setMaxResult()) really the best solution?

    Read the article

  • How to obtain JNDI data source for JPA/JTA DAO integration test?

    - by HDave
    I have a JPA application that has specified JTA transactions in persistence.xml. For whatever reason, I have found that when using JTA, you MUST specify a JNDI data source within persistence.xml as well. This is fine, unless you are trying to go integration testing outside a container and JNDI is not available. My questions are: a) is there anyway to inject a jdbc datasource into my JTA transaction manager? b) if not, how do a handle a JNDI lookup during integration testing?

    Read the article

  • JPA - Can I create an Entity class, using an @DiscriminatorValue, that doesn't have its own table?

    - by DaveyDaveDave
    Hi - this is potentially a bit complex, so I'll do my best to describe my situation - it's also my first post here, so please forgive formatting mistakes, etc! I'm using JPA with joined inheritance and a database structure that looks like: ACTION --------- ACTION_ID ACTION_MAPPING_ID ACTION_TYPE DELIVERY_CHANNEL_ACTION -------------------------- ACTION_ID CHANNEL_ID OVERRIDE_ADDRESS_ACTION -------------------------- ACTION_ID (various fields specific to this action type) So, in plain English, I have multiple different types of action, all share an ACTION_MAPPING, which is referenced from the 'parent' ACTION table. DELIVERY_CHANNEL_ACTION and OVERRIDE_ADDRESS_ACTION both have extra, supplementary data of their own, and are mapped to ACTION with a FK. Real-world, I also have a 'suppress' action, but this doesn't have any supplementary data of its own, so it doesn't have a corresponding table - all it needs is an ACTION_MAPPING, which is stored in the ACTION table. Hopefully you're with me so far... I'm creating a new project from scratch, so am pretty flexible in what I can do, but obviously would like to get it right from the outset! My current implementation, which works, has three entities loosely defined as follows: @Entity @Table(name="ACTION") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorValue("SUPPRESS") public class Action @Entity @Table(name="DELIVERY_CHANNEL_ACTION") @DiscriminatorValue("DELIVERY_CHANNEL") public class DeliveryChannelAction extends Action @Entity @Table(name="OVERRIDE_ADDRESS_ACTION") @DiscriminatorValue("OVERRIDE_ADDRESS") public class OverrideAddressAction extends Action That is - I have a concrete base class, Action, with a Joined inheritance strategy. DeliveryChannelAction and OverrideAddressAction both extend Action. What feels wrong here though, is that my Action class is the base class for these two actions, but also forms the concrete implementation for the suppress action. For the time being this works, but at some point more actions are likely to be added, and there's every chance that some of them will, like SUPPRESS, have no supplementary data, which will start to get difficult! So... what I would like to do, in the object model world, is to have Action be abstract, and create a SuppressAction class, which is empty apart from having a @DiscriminatorValue("SUPPRESS"). I've tried doing exactly what is described above, so, changing Action to: @Entity @Table(name="ACTION") @Inheritance(strategy=InheritanceType.JOINED) public abstract class Action and creating: @DiscriminatorValue("SUPPRESS") public class SuppressAction extends Action but no luck - it seems to work fine for DeliveryChannelAction and OverrideAddressAction, but when I try to create a SuppressAction and persist it, I get: java.lang.IllegalArgumentException: Object: com.mypackage.SuppressAction[actionId=null] is not a known entity type. at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4147) at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:368) at com.mypackage.test.util.EntityTestUtil.createSuppressAction(EntityTestUtil.java:672) at com.mypackage.entities.ActionTest.testCRUDAction(ActionTest.java:27) which I assume is down to the fact that SuppressAction isn't registered as an entity, but I don't know how I can do that, given that it doesn't have an associated table. Any pointers, either complete answers or hints for things to Google (I'm out of ideas!), most welcome :) EDIT: to correct my stacktrace.

    Read the article

  • How do I delete orphan entities using hibernate and JPA on a many-to-many relationship?

    - by user368453
    I want to delete orphan entities using hibernate and JPA on a many-to-many relationship but all that I found was this atibute the attribute. org.hibernate.annotations.CascadeType.DELETE_ORPHAN ( i.e. @Cascade(value={org.hibernate.annotations.CascadeType.DELETE_ORPHAN) ), which works only for one-to-many relationships. I want to know if I can delete the orphan ones on my many-to-many relationship. I´d be happy if anyone could help me... Thanks in advance !

    Read the article

  • Hibernate vs JPA vs JDO - pros and cons of each?

    - by matt b
    I'm familiar with ORM as a concept, and I've even used nHibernate several years ago for a .NET project; however, I haven't kept up with the topic of ORM in Java and haven't had a chance to use any of these tools. But, now I may have the chance to begin to use some ORM tools for one of our applications, in an attempt to move away from a series of legacy web services. I'm having a hard time telling the difference betweeen the JPA spec, what you get with the Hibernate library itself, and what JDO has to offer. So, I understand that this question is a bit open-ended, but I was hoping to get some opinions on: What are the pros and cons of each? Which would you suggest for a new project? Are there certain conditions when it would make sense to use one framework vs the other?

    Read the article

  • How to detect open database connection with Hibernate / JPA?

    - by John K
    I am learning JPA w/Hibernate using a Java SE 6 project. I'd simply like to be able to detect if the connection between Hibernate and my database (MS SQL Server) is open. For example, I'd like to be able to detect this, log it, and try reconnecting again in 60 seconds. This is what I thought would work but isOpen() doesn't appear to be what I want (always is true): EntityManagerFactory emf = Persistence.createEntityManagerFactory("rcc", props); if (emf != null && emf.isOpen()) { EntityManager em = emf.createEntityManager(); if (em == null || !emf.isOpen()) // error connecting to database else ... This seems to me to be a simple problem, but I cannot find an answer!

    Read the article

  • Using JSF, JPA and DAO. Without Spring?

    - by ich-bin-drin
    Hi, till now i still worked with JSF and JPA without DAOs. Now i'd like to use DAOs. But how can i initialize the EntityManager in the DAO-Classes? public class AdresseHome { @PersistenceContext private EntityManager entityManager; public void persist(Adresse transientInstance) { log.debug("persisting Adresse instance"); try { entityManager.persist(transientInstance); log.debug("persist successful"); } catch (RuntimeException re) { log.error("persist failed", re); throw re; } } } Have I to use Spring or is there a solution that works without Spring? Thanks.

    Read the article

  • JPA DAO integration test not throwing exception when duplicate object saved?

    - by HDave
    I am in the process of unit testing a DAO built with Spring/JPA and Hibernate as the provider. Prior to running the test, DBUnit inserted a User record with username "poweruser" -- username is the primary key in the users table. Here is the integration test method: @Test @ExpectedException(EntityExistsException.class) public void save_UserTestDataSaveUserWithPreExistingId_EntityExistsException() { User newUser = new UserImpl("poweruser"); newUser.setEmail("[email protected]"); newUser.setFirstName("New"); newUser.setLastName("User"); newUser.setPassword("secret"); dao.persist(newUser); } I have verified that the record is in the database at the start of this method. Not sure if this is relevant, but if I do a dao.flush() at the end of this method I get the following exception: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

    Read the article

  • How to Map a table with another lookup table using JPA?

    - by Sameer Malhotra
    Hi, I have two tables: 1) Application(int appid, int statusid, String appname, String appcity with getter and Setter methods) 2) App_Status(int statusid,String statusDescription with setter and getter methods) I want to map Application table with App_Status so that I don't have to query separately App_Status table in order to get the statusDescription. One thing I have to careful is that no matter what (Insert,update or delete) to the Application table the App_Status table should be unaffected means its a read only table which is maintained by the DBA internally and used only for lookup table. I am using JPA annotations so please suggest how to handle this.

    Read the article

  • JPA and aggregate functions. How do I use the result of the query?

    - by Bogdan
    Hey guys, I'm new to ORM stuff and I need some help understanding something. Let's assume I have the following standard SQL query: SELECT *, COUNT(test.testId) AS noTests FROM inspection LEFT JOIN test ON inspection.inspId = test.inspId GROUP BY inspection.inspId which I want to use in JPA. I have an Inspection entity with a one-to-many relationship to a Test entity. (an inspection has many tests) I tried writing this in JPQL: Query query = em.createQuery("SELECT insp, COUNT(???what???) FROM Inspection insp LEFT JOIN insp.testList " + "GROUP BY insp.inspId"); 1) How do I write the COUNT clause? I'd have to apply count to elements from the test table but testList is a collection, so I can't do smth like COUNT(insp.testList.testId) 2) Assuming 1 is resolved, what type of object will be returned. It will definitely not be an Inspection object... How do I use the result?

    Read the article

  • Persisting non-entity class that extends an entity (jpa) - example?

    - by Michal Minicki
    The JPA tutorial states that one can have a non-entity that extends entity class: Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. - http://java.sun.com/javaee/5/docs/tutorial/doc/bnbqa.html Is it possible to persist such structure? I want to do this: @Entity abstract class Test { ... } class FirstConcreteTest extends Test { ... } // Non-ntity class SecondConcreteTest extends Test { ... } // Non-entity Test test = new FirstConcreteTest(); em.persist(test); What I would like it to do is to persist all fields mapped on abstract Test to a common database table for all concrete classes (first and second), leaving all fields of first and second test class unpersisted (these can contain stuff like EJBs, jdbc pools, etc). And a bonus question. Is it possible to persist abstract property too? @Entity abstract class Test { @Column @Access(AccessType.PROPERTY) abstract public String getName(); } class SecondConcreteTest extends Test { public String getName() { return "Second Concrete Test"; } }

    Read the article

  • How to read changed values with native query during one transaction? (Spring and JPA)

    - by knarf1983
    We have container transaction with Spring and JPA (Hibernate). I need to make an update on a table to "flag" some rows via native statements. Then we insert some rows via EntityManager from JPATemplate to this table. After that, we need to calculate changes in the table via native statement (with Oracle's union and minus, complex groups...) I see that changes from step 1 and 2 are not commited and thats why the statement from 3 fails. I already tried with transaction propagation REQUIRES_NEW, EntityManager.flush... Didn't work. 1) update SOMETABLE acolumn = somevalue (native) 2) persist some values into SOMETABLE (via entity manager) 3) select values from SOMETABLE Is there a possibility to read the changes from step 1 and 2 in step 3?

    Read the article

  • JPA 2.0 Provider Hibernate 3.6 for DB2 v9.5 type 2 driver is throwing exception in configuration prepration

    - by Deep Saurabh
    The JPA 2.0 Provider Hibernate is throwing exception while preparing configuration for entity manager factory, I am using DB2 v9.5 database and DB2 v9.5 JDBC type 2 driver . java.sql.SQLException: [IBM][JDBC Driver] CLI0626E getDatabaseMajorVersion is not supported in this version of DB2 JDBC 2.0 driver. at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throwNotSupportedByDB2(Unknown Source) at COM.ibm.db2.jdbc.app.DB2DatabaseMetaData.getDatabaseMajorVersion(Unknown Source) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:117) at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2833) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2829) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840) at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902) at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)

    Read the article

  • How to make a mapped field inherited from a superclass transient in JPA?

    - by Russ Hayward
    I have a legacy schema that cannot be changed. I am using a base class for the common features and it contains an embedded object. There is a field that is normally mapped in the embedded object that needs to be in the persistence id for only one (of many) subclasses. I have made a new id class that includes it but then I get the error that the field is mapped twice. Here is some example code that is much simplified to maintain the sanity of the reader: @MappedSuperclass class BaseClass { @Embedded private Data data; } @Entity class SubClass extends BaseClass { @EmbeddedId private SubClassId id; } @Embeddable class Data { private int location; private String name; } @Embeddable class SubClassId { private int thingy; private int location; } I have tried @AttributeOverride but I can only get it to rename the field. I have tried to set it to updatable = false, insertable = false but this did not seem to work when used in the @AttributeOverride annotation. See answer below for the solution to this issue. I realise I could change the base class but I really do not want to split up the embedded object to separate the shared field as it would make the surrounding code more complex and require some ugly wrapping code. I could also redesign the whole system for this corner case but I would really rather not. I am using Hibernate as my JPA provider.

    Read the article

  • Why delete-orphan needs "cascade all" to run in JPA/Hibernate ?

    - by Jerome C.
    Hello, I try to map a one-to-many relation with cascade "remove" (jpa) and "delete-orphan", because I don't want children to be saved or persist when the parent is saved or persist (security reasons due to client to server (GWT, Gilead)) But this configuration doesn't work. When I try with cascade "all", it runs. Why the delete-orphan option needs a cascade "all" to run ? here is the code (without id or other fields for simplicity, the class Thread defines a simple many-to-one property without cascade): when using the removeThread function in a transactional function, it does not run but if I edit cascade.Remove into cascade.All, it runs. @Entity public class Forum { private List<ForumThread> threads; /** * @return the topics */ @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) public List<ForumThread> getThreads() { return threads; } /** * @param topics the topics to set */ public void setThreads(List<ForumThread> threads) { this.threads = threads; } public void addThread(ForumThread thread) { getThreads().add(thread); thread.setParent(this); } public void removeThread(ForumThread thread) { getThreads().remove(thread); } } thanks.

    Read the article

  • Is it possible to add JPA annotation to superclass instance variables?

    - by Kristofer Borgstrom
    Hi, I am creating entities that are the same for two different tables. In order do table mappings etc. different for the two entities but only have the rest of the code in one place - an abstract superclass. The best thing would be to be able to annotate generic stuff such as column names (since the will be identical) in the super class but that does not work because JPA annotations are not inherited by child classes. Here is an example: public abstract class MyAbstractEntity { @Column(name="PROPERTY") //This will not be inherited and is therefore useless here protected String property; public String getProperty() { return this.property; } //setters, hashCode, equals etc. methods } Which I would like to inherit and only specify the child-specific stuff, like annotations: @Entity @Table(name="MY_ENTITY_TABLE") public class MyEntity extends MyAbstractEntity { //This will not work since this field does not override the super class field, thus the setters and getters break. @Column(name="PROPERTY") protected String property; } Any ideas or will I have to create fields, getters and setters in the child classes? Thanks, Kris

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >