Search Results

Search found 960 results on 39 pages for 'annotations'.

Page 33/39 | < Previous Page | 29 30 31 32 33 34 35 36 37 38 39  | Next Page >

  • Hibernate design to speed up querying of large dataset

    - by paddydub
    I currently have the below tables representing a bus network mapped in hibernate, accessed from a Spring MVC based bus route planner I'm trying to make my route planner application perform faster, I load all the above tables into Lists to perform the route planner logic. I would appreciate if anyone has any ideas of how to speed my performace Or any suggestions of another method to approach this problem of handling a large set of data Coordinate Connections Table (INT,INT,INT, DOUBLE)( Containing 50,000 Coordinate Connections) ID, FROMCOORDID, TOCOORDID, DISTANCE 1 1 2 0.383657 2 1 17 0.173201 3 1 63 0.258781 4 1 64 0.013726 5 1 65 0.459829 6 1 95 0.458769 Coordinate Table (INT,DECIMAL, DECIMAL) (Containing 4700 Coordinates) ID , LAT, LNG 0 59.352669 -7.264341 1 59.352669 -7.264341 2 59.350012 -7.260653 3 59.337585 -7.189798 4 59.339221 -7.193582 5 59.341408 -7.205888 Bus Stop Table (INT, INT, INT)(Containing 15000 Stops) StopID RouteID COORDINATEID 1000100001 100 17 1000100002 100 18 1000100003 100 19 1000100004 100 20 1000100005 100 21 1000100006 100 22 1000100007 100 23 This is how long it takes to load all the data from each table: stop.findAll = 148ms, stops.size: 15670 Hibernate: select coordinate0_.COORDINATEID as COORDINA1_2_, coordinate0_.LAT as LAT2_, coordinate0_.LNG as LNG2_ from COORDINATES coordinate0_ coord.findAll = 51ms , coordinates.size: 4704 Hibernate: select coordconne0_.COORDCONNECTIONID as COORDCON1_3_, coordconne0_.DISTANCE as DISTANCE3_, coordconne0_.FROMCOORDID as FROMCOOR3_3_, coordconne0_.TOCOORDID as TOCOORDID3_ from COORDCONNECTIONS coordconne0_ coordinateConnectionDao.findAll = 238ms ; coordConnectioninates.size:48132 Hibernate Annotations @Entity @Table(name = "STOPS") public class Stop implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "STOPID") private int stopID; @Column(name = "ROUTEID", nullable = false) private int routeID; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "COORDINATEID", nullable = false) private Coordinate coordinate; } @Table(name = "COORDINATES") public class Coordinate { @Id @GeneratedValue @Column(name = "COORDINATEID") private int CoordinateID; @Column(name = "LAT") private double latitude; @Column(name = "LNG") private double longitude; } @Entity @Table(name = "COORDCONNECTIONS") public class CoordConnection { @Id @GeneratedValue @Column(name = "COORDCONNECTIONID") private int CoordinateID; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "FROMCOORDID", nullable = false) private Coordinate fromCoordID; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "TOCOORDID", nullable = false) private Coordinate toCoordID; @Column(name = "DISTANCE", nullable = false) private double distance; }

    Read the article

  • Servlet Mapping Help - Possible to Avoid Referencing Context Name?

    - by AJ
    Hi all, I am working on a Spring application and trying to get my URL mapping correct. What I would like to have work is the following: http://localhost:8080/idptest -> doesn't work But instead, I have to reference the context name in my URL in order to resolve the mapping: http://localhost:8080/<context_name>/idptest -> works How can I avoid the requirement of referencing the context name in my URL without using a rewrite/proxy engine e.g. Apache? Here is the servlet definition and mapping from my web.xml: <servlet> <servlet-name>idptest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/conf/idptest.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>idptest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> Here's the outline of my controller (showing annotations for request mappings): @Controller @RequestMapping("/idptest") public class MyController { @RequestMapping(method=RequestMethod.GET) public String setupForm(Model model){ MyObject someObject = new MyObject(); model.addAttribute("someObject", someObject); return "myform"; } @RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("someObject") MyObject someObject) throws Exception { // POST logic... } } Thanks!

    Read the article

  • How to store some of the entity's values in another table using hibernate?

    - by nimcap
    Hi guys, is there a simple way to persist some of the fields in another class and table using hibernate. For example, I have a Person class with name, surname, email, address1, address2, city, country fields. I want my classes to be: public class Person { private String name; private String surname; private String email; private Address address; // .. } public class Address { private Person person; // to whom this belongs private String address1; private String address2; private String city; private Address country; // .. } and I want to store Address in another table. What is the best way to achieve this? Edit: I am using annotations. It does not have to be the way I described, I am looking for best practices. PS. If there is a way to make Address immutable (to use as a value object) that is even better, or maybe not because I thought everything from wrong perspective :)

    Read the article

  • Reverse search in Hibernate Search

    - by Javi
    Hello, I'm using Hibernate Search (which uses Lucene) for searching some Data I have indexed in a directory. It works fine but I need to do a reverse search. By reverse search I mean that I have a list of queries stored in my database I need to check which one of these queries match with a Data object each time Data Object is created. I need it to alert the user when a Data Object matches with a Query he has created. So I need to index this single Data Object which has just been created and see which queries of my list has this object as a result. I've seen Lucene MemoryIndex Class to create an index in memory so I can do something like this example for every query in a list (though iterating in a Java list of queries would not be very efficient): //Iterating over my list<Query> MemoryIndex index = new MemoryIndex(); //Add all fields index.addField("myField", "myFieldData", analyzer); ... QueryParser parser = new QueryParser("myField", analyzer); float score = index.search(query); if (score > 0.0f) { System.out.println("it's a match"); } else { System.out.println("no match found"); } The problem here is that this Data Class has several Hibernate Search Annotations @Field,@IndexedEmbedded,... which indicated how fields should be indexed, so when I invoke index() method on the FullTextEntityManager instance it uses this information to index the object in the directory. Is there a similar way to index it in memory using this information? Is there a more efficient way of doing this reverse search? Thanks

    Read the article

  • @PrePersist with entity inheritance

    - by gerry
    I'm having some problems with inheritance and the @PrePersist annotation. My source code looks like the following: _the 'base' class with the annotated updateDates() method: @javax.persistence.Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Base implements Serializable{ ... @Id @GeneratedValue protected Long id; ... @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date lastModificationDate; ... public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(Date lastModificationDate) { this.lastModificationDate = lastModificationDate; } ... @PrePersist protected void updateDates() { if (creationDate == null) { creationDate = new Date(); } lastModificationDate = new Date(); } } _ now the 'Child' class that should inherit all methods "and annotations" from the base class: @javax.persistence.Entity @NamedQueries({ @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s") }) public class Sensor extends Entity { ... // additional attributes @Column(nullable=false) protected String value; ... // additional getters, setters ... } If I store/persist instances of the Base class to the database, everything works fine. The dates are getting updated. But now, if I want to persist a child instance, the database throws the following exception: MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null So, in my opinion, this is caused because in Child the method "@PrePersist protected void updateDates()" is not called/invoked before persisting the instances to the database. What is wrong with my code?

    Read the article

  • Spring 2.0.0/2.0.6 to 3.0.5 migration stories

    - by Pangea
    We are in the process of migrating to 3.0.5 of spring from 2.0.x. We mainly use spring in below scenarios custom scope: thread local scope persistence: jdbc+hibernate 3.6 (but moving to mix of ejb 3.0+jpa 2.0+hibernate, not sure if all 3 can co-exist in 1 app) transactions: local (but planning to use jta due to the necessity of using multiple persistence inits, and has to use ejb+jpa+hibernate in 1 single trans), declarative trans mgmt parent-child contexts cxf annotations+xml OracleLobHandler Resource/ResourceBundleMessageResource JSF/Facelets with FacesSpringVariableResolver ActiveMQ integration Quartz integration TaskExecutor JMX exporter HttpExporter/Invoker Appreciate if someone can share their experiences like what to watch out for head aches/pain points which ones to drop for better alternate choices in new 3.0.5 release Is it better to switch from commons/iscreen validator to Hibernate Validator (Spec impl) or Spring Validator Is there a bean mapping framework in spring that i can use instead of Dozer XSLT transformation helper: currently we have small homegrown framework to cache xslts during load. if spring can do that for me then I would like to drop this Encryption/Decryption support. Password generation support. Authentication with SALT any SAML (or claims based secur New ideas Suggestions Switch to latest version of aspectj Upgrade guide from 2.5 to 3.0.5

    Read the article

  • jndi binding on jboss4.2.3 and ejb3

    - by broschb
    I am trying to deploy a stateless ejb on jboss 4.2.3 using ejb3 annotations. Everything builds and deploys correctly, and I do not get any errors when jboss starts up. However the ejb is not getting bound to any JNDI location for lookup when I look at the bindings in jboss. Below is what I have for my ejb. Remote @Remote public interface TestWebService { public String TestWebMethod(String param1, String param2); } Stateless EJB @Stateless @RemoteBinding(jndiBinding="TestWeb") @Remote(TestWebService.class) public class TestWebServiceBean implements TestWebService{ public String TestWebMethod(String param1, String param2) { System.out.println("HELLO "+param1+" "+param2); return "Welcome!!"; } } I have tried not having the @Remote and @RemoteBinding and it doesn't make a difference. I have also added and ejb-jar.xml file (which should not be needed with ejb3) and that does not appear to make a difference. Below is the output I see in the jboss log on startup. installing MBean: jboss.j2ee:ear=ejb_web_service_ear-0.0.1- SNAPSHOT.ear,jar=ejb_web_service-0.0.1-SNAPSHOT.jar,name=TestWebServiceBean,service=EJB3 with dependencies: 21:56:00,633 INFO [EJBContainer] STARTED EJB: com.tomax.ejb.TestWebServiceBean ejbName: TestWebServiceBean

    Read the article

  • How can I marshal JSON to/from a POJO for BlackBerry Java?

    - by sowbug
    I'm writing a RIM BlackBerry client app. BlackBerry uses a simplified version of Java (no generics, no annotations, limited collections support, etc.; roughly a Java 1.3 dialect). My client will be speaking JSON to a server. We have a bunch of JAXB-generated POJOs, but they're heavily annotated, and they use various classes that aren't available on this platform (ArrayList, BigDecimal, XMLGregorianCalendar). We also have the XSD used by the JAXB-XJC compiler to generate those source files. Being the lazy programmer that I am, I'd really rather not manually translate the existing source files to Java 1.3-compatible JSON-marshalling classes. I already tried JAXB 1.0.6 xjc. Unfortunately, it doesn't understand the XSD file well enough to emit proper classes. Do you know of a tool that will take JAXB 2.0 XSD files and emit Java 1.3 classes? And do you know of a JSON marshalling library that works with old Java? I think I am doomed because JSON arrived around 2006, and Java 5 was released in late 2004, meaning that people probably wouldn't be writing JSON-parsing code for old versions of Java. However, it seems that there must be good JSON libraries for J2ME, which is why I'm holding out hope.

    Read the article

  • Lucene Query Syntax

    - by Don
    Hi, I'm trying to use Lucene to query a domain that has the following structure Student 1-------* Attendance *---------1 Course The data in the domain is summarised below Course.name Attendance.mandatory Student.name ------------------------------------------------- cooking N Bob art Y Bob If I execute the query "courseName:cooking AND mandatory:Y" it returns Bob, because Bob is attending the cooking course, and Bob is also attending a mandatory course. However, what I really want to query for is "students attending a mandatory cooking course", which in this case would return nobody. Is it possible to formulate this as a Lucene query? I'm actually using Compass, rather than Lucene directly, so I can use either CompassQueryBuilder or Lucene's query language. For the sake of completeness, the domain classes themselves are shown below. These classes are Grails domain classes, but I'm using the standard Compass annotations and Lucene query syntax. @Searchable class Student { @SearchableProperty(accessor = 'property') String name static hasMany = [attendances: Attendance] @SearchableId(accessor = 'property') Long id @SearchableComponent Set<Attendance> getAttendances() { return attendances } } @Searchable(root = false) class Attendance { static belongsTo = [student: Student, course: Course] @SearchableProperty(accessor = 'property') String mandatory = "Y" @SearchableId(accessor = 'property') Long id @SearchableComponent Course getCourse() { return course } } @Searchable(root = false) class Course { @SearchableProperty(accessor = 'property', name = "courseName") String name @SearchableId(accessor = 'property') Long id }

    Read the article

  • Hibernate MapKeyManyToMany gives composite key where none exists

    - by larsrc
    I have a Hibernate (3.3.1) mapping of a map using a three-way join table: @Entity public class SiteConfiguration extends ConfigurationSet { @ManyToMany @MapKeyManyToMany(joinColumns=@JoinColumn(name="SiteTypeInstallationId")) @JoinTable( name="SiteConfig_InstConfig", joinColumns = @JoinColumn(name="SiteConfigId"), inverseJoinColumns = @JoinColumn(name="InstallationConfigId") ) Map<SiteTypeInstallation, InstallationConfiguration> installationConfigurations = new HashMap<SiteTypeInstallation, InstallationConfiguration>(); ... } The underlying table (in Oracle 11g) is: Name Null Type ------------------------------ -------- ---------- SITECONFIGID NOT NULL NUMBER(19) SITETYPEINSTALLATIONID NOT NULL NUMBER(19) INSTALLATIONCONFIGID NOT NULL NUMBER(19) The key entity used to have a three-column primary key in the database, but is now redefined as: @Entity public class SiteTypeInstallation implements IdResolvable { @Id @GeneratedValue(generator="SiteTypeInstallationSeq", strategy= GenerationType.SEQUENCE) @SequenceGenerator(name = "SiteTypeInstallationSeq", sequenceName = "SEQ_SiteTypeInstallation", allocationSize = 1) long id; @ManyToOne @JoinColumn(name="SiteTypeId") SiteType siteType; @ManyToOne @JoinColumn(name="InstalationRoleId") InstallationRole role; @ManyToOne @JoinColumn(name="InstallationTypeId") InstType type; ... } The table for this has a primary key 'Id' and foreign key constraints+indexes for each of the other columns: Name Null Type ------------------------------ -------- ---------- SITETYPEID NOT NULL NUMBER(19) INSTALLATIONROLEID NOT NULL NUMBER(19) INSTALLATIONTYPEID NOT NULL NUMBER(19) ID NOT NULL NUMBER(19) For some reason, Hibernate thinks the key of the map is composite, even though it isn't, and gives me this error: org.hibernate.MappingException: Foreign key (FK1A241BE195C69C8:SiteConfig_InstConfig [SiteTypeInstallationId])) must have same number of columns as the referenced primary key (SiteTypeInstallation [SiteTypeId,InstallationRoleId]) If I remove the annotations on installationConfigurations and make it transient, the error disappears. I am very confused why it thinks SiteTypeInstallation has a composite key at all when @Id is clearly defining a simple key, and doubly confused why it picks exactly just those two columns. Any idea why this happens? Is it possible that JBoss (5.0 EAP) + Hibernate somehow remembers a mistaken idea of the primary key across server restarts and code redeployments? Thanks in advance, -Lars

    Read the article

  • ResourceFilterFactory and non-Path annotated Resources

    - by tousdan
    (I'm using Jersey 1.7) I am attempting to add a ResourceFilterFactory in my project to select which filters are used per method using annotations. The ResourceFilterFactory seems to be able to filters on Resources which are annotated with the Path annotation but it would seem that it does not attempt to generate filters for the methods of the SubResourceLocator of the resources that are called. @Path("a") public class A { //sub resource locator? @Path("b") public B getB() { return new B(); } @GET public void doGet() {} } public class B { @GET public void doOtherGet() { } @Path("c") public void doInner() { } } When ran, the Filter factory will only be called for the following: AbstractResourceMethod(A#doGet) AbstractSubResourceLocator(A#getB) When I expected it to be called for every method of the sub resource. I'm currently using the following options in my web.xml; <init-param> <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name> <param-value>com.my.MyResourceFilterFactory</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.my.resources</param-value> </init-param> Is my understanding of the filter factory flawed?

    Read the article

  • What is the IoC / "Springy" way to handle MVP in GWT? (Hint, probably not the Spring Roo 1.1 way)

    - by Ehrann Mehdan
    This is the Spring Roo 1.1 way of doing a factory that returns a GWT Activity (Yes, Spring Framework) public Activity getActivity(ProxyPlace place) { switch (place.getOperation()) { case DETAILS: return new EmployeeDetailsActivity((EntityProxyId<EmployeeProxy>)place.getProxyId(), requests, placeController, ScaffoldApp.isMobile() ? EmployeeMobileDetailsView.instance() : EmployeeDetailsView.instance()); case EDIT: return makeEditActivity(place); case CREATE: return makeCreateActivity(); } throw new IllegalArgumentException("Unknown operation " + place.getOperation()); } It seems to me that we just went back hundred of years if we use a switch case with constants to make a factory. Now this is official auto generated Spring roo 1.1 with GWT / GAE integration, I kid you not I can only assume this is some executives empty announcements because this is definitly not Spring It seems VMWare and Google were too fast to get something out and didn't quite finish it, isn't it? Am I missing something or this is half baked and by far not the way Spring + GWT MVP should work? Do you have a better example of how Spring, GWT (2.1 MVP approach) and GAE should connect? I would hate to do all the plumbing of managing history and activities like this. (no annotations? IOC?) I also would hate to reinvent the wheel and write my own Spring enhancement just to find someone else did the same, or worse, find out that SpringSource and Google will release roo 1.2 soon and make it right

    Read the article

  • Problem using the prependTo() in jQuery

    - by raulriera
    Hi all, I am having a problem trying to use the prependTo() function in jQuery... for some reason I can't get this to work $(" <div id="note178" class="note"> <div class="delete"><a href="/chart-notes/delete/178" onclick="$.ajax({ dataType: 'script', url: '/chart-notes/delete/178'}); return false;"><img src='/images/icons/delete.png'></a></div> <div class="timestamp">1 minute ago </div> <div class="content">ñasdas dasdasdasd conclusión</div> </div> ").prependTo(".notes").fadeIn("slow"); Although when doing it like this, it works fine $.ajax({ url:'/chart-notes/show/<cfoutput>#chartnote.id#</cfoutput>', success: function(data) { $(data).prependTo(".notes").fadeIn("slow"); // Scroll to the top of the annotations $('html, body').animate({scrollTop: $(".notes").offset().top}, 1000); // Clear the form $('#chartnote-notes').val(""); } }); The "data" response from that success function is the same <div id="note178" class="note"> <div class="delete"><a href="/chart-notes/delete/178" onclick="$.ajax({ dataType: 'script', url: '/chart-notes/delete/178'}); return false;"><img src='/images/icons/delete.png'></a></div> <div class="timestamp">1 minute ago </div> <div class="content">ñasdas dasdasdasd conclusión</div> </div> As before

    Read the article

  • JPA 2.0 Provider Hibernate

    - by Rooh
    I have very strange problem we are using jpa 2.0 with hibernate annotations based Database generated through JPA DDL is true and MySQL as Database; i will provide some reference classes and then my porblem. @MappedSuperclass public abstract class Common implements serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false) private Long id; @ManyToOne @JoinColumn private Address address; //with all getter and setters //as well equal and hashCode } @Entity public class Parent extends Common{ private String name; @OneToMany(cascade = {CascadeType.MERGE,CascadeType.PERSIST}, mappedBy = "parent") private List<Child> child; //setters and rest of class } @Entity public class Child extends Common{ //some properties with getter/setters } @Entity public class Address implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false) private Long id; private String street; //rest of class with get/setter } as in code you can see that parents and child classes extends Common class so both have address property and id , the problem occurs when change the address refference in parent class it reflect same change in all child objects in list and if change address refference in child class then on merge it will change address refference of parent as well i am not able to figure out is it is problem of jpa or hibernate

    Read the article

  • cancelPreviousPerformRequestWithTarget is not canceling my previously delayed thread started with pe

    - by jmurphy
    Hello, I've launched a delayed thread using performSelector but the user still has the ability to hit the back button on the current view causing dealloc to be called. When this happens my thread still seems to be called which causes my app to crash because the properties that thread is trying to write to have been released. To solve this I am trying to call cancelPreviousPerformRequestsWithTarget to cancel the previous request but it doesn't seem to be working. Below are some code snippets. - (void) viewDidLoad { [self performSelector:@selector(myStopUpdatingLocation) withObject:nil afterDelay:6]; } (void)viewWillDisappear:(BOOL)animated { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(myStopUpdatingLocation) object:nil]; } Am I doing something incorrect here? The method myStopUpdatingLocation is defined in the same class that I'm calling the perform requests. A little more background. The function that I'm trying to implement is to find a users location, search google for some locations around that location and display several annotations on the map. On viewDidLoad I start updating the location with CLLocationManager. I've build in a timeout after 6 seconds if I don't get my desired accuracy within the timeout and I'm using a performSelector to do this. What can happen is the user clicks the back button in the view and this thread will still execute even though all my properties have been released causing a crash. Thanks in advance! James

    Read the article

  • Is the REST support in Spring 3's MVC Framework production quality yet?

    - by glenjohnson
    Hi all, Since Spring 3 was released in December last year, I have been trying out the new REST features in the MVC framework for a small commercial project involving implementing a few RESTful Web Services which consume XML and return XML views using JiBX. I plan to use either Hibernate or JDBC Templates for the data persistence. As a Spring 2.0 developer, I have found Spring 3's (and 2.5's) new annotations way of doing things quite a paradigm shift and have personally found some of the new MVC annotation features difficult to get up to speed with for non-trivial applications - as such, I am often having to dig for information in forums and blogs that is not apparent from going through the reference guide or from the various Spring 3 REST examples on the web. For deadline-driven production quality and mission critical applications implementing a RESTful architecture, should I be holding off from Spring 3 and rather be using mature JSR 311 (JAX-RS) compliant frameworks like RESTlet or Jersey for the REST layer of my code (together with Spring 2 / 2.5 to tie things together)? I had no problems using RESTlet 1.x in a previous project and it was quite easy to get up to speed with (no magic tricks behind the scenes), but when starting my current project it initially looked like the new REST stuff in Spring 3's MVC Framework would make life easier. Do any of you out there have any advice to give on this? Does anyone know of any commercial / production-quality projects using, or having successfully delivered with, the new REST stuff in Spring 3's MVC Framework. Many thanks Glen

    Read the article

  • Going "behind Hibernate's back" to update foreign key values without an associated entity

    - by Alex Cruise
    Updated: I wound up "solving" the problem by doing the opposite! I now have the entity reference field set as read-only (insertable=false updatable=false), and the foreign key field read-write. This means I need to take special care when saving new entities, but on querying, the entity properties get resolved for me. I have a bidirectional one-to-many association in my domain model, where I'm using JPA annotations and Hibernate as the persistence provider. It's pretty much your bog-standard parent/child configuration, with one difference being that I want to expose the parent's foreign key as a separate property of the child alongside the reference to a parent instance, like so: @Entity public class Child { @Id @GeneratedValue Long id; @Column(name="parent_id", insertable=false, updatable=false) private Long parentId; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="parent_id") private Parent parent; private long timestamp; } @Entity public class Parent { @Id @GeneratedValue Long id; @OrderBy("timestamp") @OneToMany(mappedBy="parent", cascade=CascadeType.ALL, fetch=FetchType.LAZY) private List<Child> children; } This works just fine most of the time, but there are many (legacy) cases when I'd like to put an invalid value in the parent_id column without having to create a bogus Parent first. Unfortunately, Hibernate won't save values assigned to the parentId field due to insertable=false, updatable=false, which it requires when the same column is mapped to multiple properties. Is there any nice way to "go behind Hibernate's back" and sneak values into that field without having to drop down to JDBC or implement an interceptor? Thanks!

    Read the article

  • Firefox extension: How to inject javascript into page and run it?

    - by el griz
    I'm writing a Firefox extension to allow users to annotate any page with text and/or drawings and then save an image of the page including the annotations. Use cases would be clients reviewing web pages, adding feedback to the page, saving the image of this and emailing it back to the web developer or testers taking annotated screenshots of GUI bugs etc. I wrote the annotation/drawing functionality in javascript before developing the extension. This script adds a <canvas> element to the page to draw upon as well as a toolbar (in a <div>) that contains buttons (each <canvas> elements) for the different draw tools e.g. line, box, ellipse, text, etc. This works fine when manually included in a page. I now need a way for the extension to: Inject this script into any page including pages I don't control. This needs to occur when the user invokes the extension, which can be after the page has loaded. Once injected the init() function in this script that adds the canvas and toolbar elements etc. needs to be run somehow, but I can't determine how to call this from the extension. Note that once injected I don't need this script to interact with the extension (as the extension just takes a screenshot of the entire document (and removes the added page elements) when the user presses the save button in the extension chrome).

    Read the article

  • What is best practice about having one-many hibernate

    - by Patrick
    Hi all, I believe this is a common scenario. Say I have a one-many mapping in hibernate Category has many Item Category: @OneToMany( cascade = {CascadeType.ALL},fetch = FetchType.LAZY) @JoinColumn(name="category_id") @Cascade( value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN ) private List<Item> items; Item: @ManyToOne(targetEntity=Category.class,fetch=FetchType.EAGER) @JoinColumn(name="category_id",insertable=false,updatable=false) private Category category; All works fine. I use Category to fully control Item's life cycle. But, when I am writing code to update Category, first I get Category out from DB. Then pass it to UI. User fill in altered values for Category and pass back. Here comes the problem. Because I only pass around Category information not Item. Therefore the Item collection will be empty. When I call saveOrUpdate, it will clean out all associations. Any suggestion on what's best to address this? I think the advantage of having Category controls Item is to easily main the order of Item and not to confuse bi-directly. But what about situation that you do want to just update Category it self? Load it first and merge? Thank you.

    Read the article

  • Best approach for Java/Maven/JPA/Hibernate build with multiple database vendor support?

    - by HDave
    I have an enterprise application that uses a single database, but the application needs to support mysql, oracle, and sql*server as installation options. To try to remain portable we are using JPA annotations with Hibernate as the implementation. We also have a test-bed instance of each database running for development. The app is building nicely in Maven, and I've played around with the hibernate3-maven-plugin and can auto-generate DDL for a given database dialect. What is the best way to approach this so that individual developers can easily test against all three databases and our Hudson based CI server can build things propertly. More specifically: 1) I thought the hbm2ddl goal in the hibernate3-maven-plugin would just generate a schema file, but apparently it connects to a live database and attempts to create the schema. Is there a way to have this just create the schema file for each database dialect without connecting to a database? 2) If the hibernate3-maven-plug insists on actually creating the database schema, is there a way to have it drop the database and recreate it before creating the schema? 3) I am thinking that each developer (and the hudson build machine) should have their own separate database on each database server. Is this typical? 4) Will developers have to run Maven three times...once for each database vendor? If so, how do I merge the results on the build machine? 5) There is a hbm2doc goal within hibernate3-maven-plugin. It seems overkill to run this three times...I gotta believe it'd be nearly identical for each database.

    Read the article

  • Setting up relations/mappings for a SQLAlchemy many-to-many database

    - by Brent Ramerth
    I'm new to SQLAlchemy and relational databases, and I'm trying to set up a model for an annotated lexicon. I want to support an arbitrary number of key-value annotations for the words which can be added or removed at runtime. Since there will be a lot of repetition in the names of the keys, I don't want to use this solution directly, although the code is similar. My design has word objects and property objects. The words and properties are stored in separate tables with a property_values table that links the two. Here's the code: from sqlalchemy import Column, Integer, String, Table, create_engine from sqlalchemy import MetaData, ForeignKey from sqlalchemy.orm import relation, mapper, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///test.db', echo=True) meta = MetaData(bind=engine) property_values = Table('property_values', meta, Column('word_id', Integer, ForeignKey('words.id')), Column('property_id', Integer, ForeignKey('properties.id')), Column('value', String(20)) ) words = Table('words', meta, Column('id', Integer, primary_key=True), Column('name', String(20)), Column('freq', Integer) ) properties = Table('properties', meta, Column('id', Integer, primary_key=True), Column('name', String(20), nullable=False, unique=True) ) meta.create_all() class Word(object): def __init__(self, name, freq=1): self.name = name self.freq = freq class Property(object): def __init__(self, name): self.name = name mapper(Property, properties) Now I'd like to be able to do the following: Session = sessionmaker(bind=engine) s = Session() word = Word('foo', 42) word['bar'] = 'yes' # or word.bar = 'yes' ? s.add(word) s.commit() Ideally this should add 1|foo|42 to the words table, add 1|bar to the properties table, and add 1|1|yes to the property_values table. However, I don't have the right mappings and relations in place to make this happen. I get the sense from reading the documentation at http://www.sqlalchemy.org/docs/05/mappers.html#association-pattern that I want to use an association proxy or something of that sort here, but the syntax is unclear to me. I experimented with this: mapper(Word, words, properties={ 'properties': relation(Property, secondary=property_values) }) but this mapper only fills in the foreign key values, and I need to fill in the other value as well. Any assistance would be greatly appreciated.

    Read the article

  • Hibernate collection multiple types

    - by CaptainAwesomePants
    I have a class Player that contains a list of Accessory objects. There are two kinds of Accessories. SocketedAccessories have a list of SocketJewels, and MagicAccessories have a list of MagicEnchantments. At the database level, there is a players table that represents the player, and an accessories table that contains a list of accessories. Accessories have a type field that indicates whether they are socketed or magical, and the columns that are only used by one type are just left blank by entries of the other type. There are socket_jewels and magic_enchantments tables, representing the socket jewels or the magic enchantments on each accessory. I am trying to figure out the correct way to map this with Hibernate. One way would be for the player to have two lists of accessories, one for SocketedAccessories and one for MagicAccessories. That seems undesirable, though. What I want is a way to specify that player should have a field List<Accessory> accessories that contains both types of thing. Is there a way to tell Hibernate, in either hbm.xml or annotations, to do this?

    Read the article

  • MVC2 Modelbinder for List of derived objects

    - by user250773
    I want a list of different (derived) object types working with the Default Modelbinder in Asp.net MVC 2. I have the following ViewModel: public class ItemFormModel { [Required(ErrorMessage = "Required Field")] public string Name { get; set; } public string Description { get; set; } [ScaffoldColumn(true)] //public List<Core.Object> Objects { get; set; } public ArrayList Objects { get; set; } } And the list contains objects of diffent derived types, e.g. public class TextObject : Core.Object { public string Text { get; set; } } public class BoolObject : Core.Object { public bool Value { get; set; } } It doesn't matter if I use the List or the ArrayList implementation, everything get's nicely scaffolded in the form, but the modelbinder doesn't resolve the derived object type properties for me when posting back to the ActionResult. What could be a good solution for the Viewmodel structure to get a list of different object types handled? Having an extra list for every object type (e.g. List, List etc.) seems to be not a good solution for me, since this is a lot of overhead both in building the viewmodel and mapping it back to the domain model. Thinking about the other approach of binding all properties in a custom model binder, how can I make use the data annotations approach here (validating required attributes etc.) without a lot of overhead?

    Read the article

  • Initializing Detail View from nib with parameters passed from Root View

    - by culov
    I'm have a map view with a number of annotations on it... once the callout is clicked, i need to pass several parameters to the DetailViewController, so ive been trying to do this through the constructor. I've debugged a bit and discovered that the arguments are being passed properly and are being received as expected within the constructor, but for some reason whenever I try to change the values of the IBOutlets I've positioned in the nib, it never has an effect. Here's what im passing (btw, im getting a "No initWithNibName : bundle : header' method found" warning at this line): DetailViewController *dvc = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil header:headerText]; [self.navigationController pushViewController:dvc animated:YES]; Now heres my constructor: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil header:(UILabel*)headerLabel { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { self.headerTextView = headerLabel; NSLog(@"header:%@", headerLabel.text); } return self; } Once again, the problem is that headerLabel.text is printed properly in the console, but the line self.headerTextView = headerLabel; doesnt seem to be doing what I want it to do. Thanks!

    Read the article

  • ManyToOne annotation fails with Hibernate 4.1: MappingException

    - by barelas
    Using Hibernate 4.1.1.Final. When I try to add @ManyToOne, schema creation fails with: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister User.java: @Entity public class User { @Id private int id; public int getId() {return id;} public void setId(int id) {this.id = id;} @ManyToOne Department department; public Department getDepartment() {return department;} public void setDepartment(Department department) {this.department = department;} } Department.java @Entity public class Department { @Id private int departmentNumber; public int getDepartmentNumber() {return departmentNumber;} public void setDepartmentNumber(int departmentNumber) {this.departmentNumber = departmentNumber;} } hibernate.properties: hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/dbname hibernate.connection.username=user hibernate.connection.password=pass hibernate.connection.pool_size=5 hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect hibernate.hbm2ddl.auto=create init (throwing exception): ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().buildServiceRegistry(); sessionFactory = new MetadataSources( serviceRegistrY.addAnnotatedClass(Department.class).addAnnotatedClass(User.class).buildMetadata().buildSessionFactory(); exception throwed at init: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:174) at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:148) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:820) at org.hibernate.metamodel.source.internal.SessionFactoryBuilderImpl.buildSessionFactory(SessionFactoryBuilderImpl.java:65) at org.hibernate.metamodel.source.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:340) I have tried adding some other annotations, but shouldn't the defaults work and create the tables and foreign key? If I remove the department from User, tables get generated fine. Thanks in advance!

    Read the article

< Previous Page | 29 30 31 32 33 34 35 36 37 38 39  | Next Page >