Search Results

Search found 2391 results on 96 pages for 'hibernate'.

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

  • 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

  • Maven Java Source Code Generation for Hibernate

    - by Adam
    Hi, I´m busy converting an existing project from an Ant build to one using Maven. Part of this build includes using the hibernate hbm2java tool to convert a collection of .hbm.xml files into Java. Here's a snippet of the Ant script used to do this: <target name="dbcodegen" depends="cleangen" description="Generate Java source from Hibernate XML"> <hibernatetool destdir="${src.generated}"> <configuration> <fileset dir="${src.config}"> <include name="**/*.hbm.xml"/> </fileset> </configuration> <hbm2java jdk5="true"/> </hibernatetool> </target> I've had a look around on the internet and some people seem to do this (I think) using Ant within Maven and others with the Maven plugin. I'd prefer to avoid mixing Ant and Maven. Can anyone suggest a way to do this so that all of the .hbm.xml files are picked up and the code generation takes place as part of the Maven code generation build phase? Thanks! Adam.

    Read the article

  • Hibernate collection mapping challenge

    - by Geln Yang
    Hi, There is a table Item like, code,name 01,parent1 02,parent2 0101,child11 0102,child12 0201,child21 0202,child22 Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two character of its code : class Item{ string code; string name; Item parent; List<Item> children; .... setter/getter.... } <hibernate-mapping> <class name="Item" table="Item"> <id name="code" length="4" type="string"> <generator class="assigned" /> </id> <property name="name" column="name" length="50" not-null="true" /> <!--====================================== --> <many-to-one name="parent" class="Item" not-found="ignore"></many-to-one> <bag name="children"></bag> <!--====================================== --> </class> </hibernate-mapping> How to definition the mapping relationship? Thanks!

    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

  • Hibernate collection mapping Problem

    - by Geln Yang
    Hi, There is a table Item like, code,name 01,parent1 02,parent2 0101,child11 0102,child12 0201,child21 0202,child22 Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two characters of its code : class Item{ String code; String name; Item parent; List<Item> children; .... setter/getter.... } <hibernate-mapping> <class name="Item" table="Item"> <id name="code" length="4" type="string"> <generator class="assigned" /> </id> <property name="name" column="name" length="50" not-null="true" /> <many-to-one name="parent" class="Item" not-found="ignore"> <formula> <![CDATA[ (select i.code,r.name from Item i where (case length(code) when 4 then i.code=SUBSTRING(code,1,2) else false end)) ]]> </formula> </many-to-one> <bag name="children"></bag> </class> </hibernate-mapping> I try to use formula to define the many-to-one relationship,but it doesn't work!Is there something wrong?Or is there other method? Thanks! ps,I use mysql database.

    Read the article

  • Hibernate mapping Problem

    - by Geln Yang
    Hi, There is a table Item like, code,name 01,parent1 02,parent2 0101,child11 0102,child12 0201,child21 0202,child22 Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two characters of its code : class Item{ String code; String name; Item parent; List<Item> children; .... setter/getter.... } <hibernate-mapping> <class name="Item" table="Item"> <id name="code" length="4" type="string"> <generator class="assigned" /> </id> <property name="name" column="name" length="50" not-null="true" /> <many-to-one name="parent" class="Item" not-found="ignore"> <formula> <![CDATA[ (select i.code,r.name from Item i where (case length(code) when 4 then i.code=SUBSTRING(code,1,2) else false end)) ]]> </formula> </many-to-one> <bag name="children"></bag> </class> </hibernate-mapping> I try to use formula to define the many-to-one relationship,but it doesn't work!Is there something wrong?Or is there other method? Thanks! ps,I use mysql database.

    Read the article

  • Understanding Hibernate saveOrUpdate and the Persistence Life Cycle

    - by Stephano
    The books that I've read regarding hibernate are, at best, reference tomes. They very seldom have good code examples, so I tend to use online resources for those needs. However, I've always had a problem understanding the basic idea of hibernate persistence. I've read the books and understand the concepts, but in practice, I often see results that I don't understand. Perhaps you all can help, as you have in the past. Let's look at a simple example of a dog and a cat that are friends. This isn't a rare occurrence. It also has the benefit of being much more interesting than my business case. We want a function called "saveFriends" that takes a dog name and a cat name. We'll save the Dog and then the Cat. For this example to work, the cat is going to have a reference back to the dog. I understand this isn't an ideal example, but it's cute and works for our purposes. FriendService.java public int saveFriends(String dogName, String catName) { Dog fido = new Dog(); Cat felix = new Cat(); fido.name = dogName; fido = animalDao.saveDog(fido); felix.name = catName; [ex.A]felix.friend = fido; [ex.B]felix.friend = animalDao.getDogByName(dogName); animalDao.saveCat(felix); } AnimalDao.java (extends HibernateDaoSupport) public Dog saveDog(Dog dog) { getHibernateTemplate().saveOrUpdate(dog); return dog } public Cat saveCat(Cat cat) { getHibernateTemplate().saveOrUpdate(cat); return cat; } public Dog getDogByName(String name) { return (Dog) getHibernateTemplate().find("from Dog where name=?", name).get(0); } Now, assume for a minute that I would like to use either example A or example B to save my friend. Is one better than the other to use? I'll understand if neither of those examples work, but please explain why.

    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

  • 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

  • Object equality in context of hibernate / webapp

    - by bert
    How do you handle object equality for java objects managed by hibernate? In the 'hibernate in action' book they say that one should favor business keys over surrogate keys. Most of the time, i do not have a business key. Think of addresses mapped to a person. The addresses are keeped in a Set and displayed in a Wicket RefreshingView (with a ReuseIfEquals strategy). I could either use the surrogate id or use all fields in the equals() and hashCode() functions. The problem is that those fields change during the lifetime ob the object. Either because the user entered some data or the id changes due to JPA merge() being called inside the OSIV (Open Session in View) filter. My understanding of the equals() and hashCode() contract is that those should not change during the lifetime of an object. What i have tried so far: equals() based on hashCode() which uses the database id (or super.hashCode() if id is null). Problem: new addresses start with an null id but get an id when attached to a person and this person gets merged() (re-attached) in the osiv-filter. lazy compute the hashcode when hashCode() is first called and make that hashcode @Transitional. Does not work, as merge() returns a new object and the hashcode does not get copied over. What i would need is an ID that gets assigned during object creation I think. What would be my options here? I don't want to introduce some additional persistent property. Is there a way to explicitly tell JPA to assign an ID to an object? Regards

    Read the article

  • Hibernate Search + Spring

    - by Zane
    I'm trying to integrate Hibernate Search with Spring, but I can't seem to index anything. I was able to get Hibernate Search to work without Spring, but I'm having a problem integrating it with Spring. Any help would be much appreciated. Below is my springmvc-servlet.xml: <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="enewsclipsPersistenceUnit" /> </bean> And here is my DAO class: @Repository public class SearchDaoImpl implements SearchDao { JpaTemplate jpaTemplate; @Autowired public SearchDaoImpl(EntityManagerFactory entityManagerFactory) { this.jpaTemplate = new JpaTemplate(entityManagerFactory); } @SuppressWarnings("unchecked") public void updateSearchIndex() { /* Implement the callback method */ jpaTemplate.execute(new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { List<Article> articles = em.createQuery("select a from Article a").getResultList(); FullTextEntityManager ftEm = Search.getFullTextEntityManager(em); ftEm.getTransaction().begin(); for(Article article : articles) { System.out.println("Indexing Item " + article.getTitle()); ftEm.index(article); } ftEm.getTransaction().commit(); return null; } }); } } I think that it may have to do with the transactions but I'm not exactly sure. If you could just point me in the right direction, that would be helpful too! Thank you.

    Read the article

  • JPA/Hibernate Parent/Child relationship

    - by NubieJ
    Hi I am quite new to JPA/Hibernate (Java in general) so my question is as follows (note, I have searched far and wide and have not come across an answer to this): I have two entities: Parent and Child (naming changed). Parent contains a list of Children and Children refers back to parent. e.g. @Entity public class Parent { @Id @Basic @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "PARENT_ID", insertable = false, updatable = false) private int id; /* ..... */ @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY) @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", nullable = true) private Set<child> children; /* ..... */ } @Entity public class Child { @Id @Basic @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "CHILD_ID", insertable = false, updatable = false) private int id; /* ..... */ @ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID") private Parent parent; /* ..... */ } I want to be able to do the following: Retrieve a Parent entity which would contain a list of all its children (List), however, when listing Parent (getting List, it of course should omit the children from the results, therefore setting FetchType.LAZY. Retrieve a Child entity which would contain an instance of the Parent entity. Using the code above (or similar) results in two exceptions: Retrieving Parent: A cycle is detected in the object graph. This will cause infinitely deep XML... Retrieving Child: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxxxxxxxxxx, no session or session was closed When retrieving the Parent entity, I am using a named query (i.e. calling it specifically) @NamedQuery(name = "Parent.findByParentId", query = "SELECT p FROM Parent AS p LEFT JOIN FETCH p.children where p.id = :id") Code to get Parent (i.e. service layer): public Parent findByParentId(int parentId) { Query query = em.createNamedQuery("Parent.findByParentId"); query.setParameter("id", parentId); return (Parent) query.getSingleResult(); } Why am I getting a LazyInitializationException event though the List property on the Parent entity is set as Lazy (when retrieving the Child entity)?

    Read the article

  • Java-Hibernate: How can I translate these tables to hibernate annotations?

    - by penas
    I need to create a simple application using these tables: http://stackoverflow.com/questions/2612848/are-these-tables-respect-the-3nf-database-normalization I have created the application using simple old JDBC, but I would like to see how the application would look like using Hibernate, but I don't know how to put the sql code in java. I have found LOTS of examples, but I'm pretty much confused about using Hibernate and I don't know If I made such a good joob. For example, for the first three tables: AUTHOR table * Author_ID, PK * First_Name * Last_Name TITLES table * TITLE_ID, PK * NAME * Author_ID, FK DOMAIN table * DOMAIN_ID, PK * NAME * TITLE_ID, FK The code in java: Table 1 @Entity @Table(name = "AUTHORS", schema = "LIBRARY") public class Author{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "Author_ID") private int authorId; @Column(name = "First_Name", nullable = false, length = 50) private String firstName; @Column(name = "Last_Name", nullable = false, length = 40) private String lastName; @OneToMany @JoinColumn(name = "Title_ID") private List<Title> titles; Table 2 @Entity @Table(name = "TITLES") public class Title{ @Id @Column(name = "Title_ID") private int titleID; @Column(name = "Name", nullable = false, length = 50) private String name; @ManyToOne @JoinColumn(name = "Domain_ID") private Domain domains; Table 3 @Entity @Table(name = "DOMAINS") public class Domain{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "Domain_ID") private int Domain_ID; @Column(name = "Name", nullable = false, length = 50) private String name; @OneToOne(mappedBy = "domains") private Title title; } Any good? :)

    Read the article

  • Hibernate: fetching multiple bags efficiently

    - by Jens Jansson
    Hi! I'm developing a multilingual application. For this reason many objects have in their name and description fields collections of something I call LocalizedStrings instead of plain strings. Every LocalizedString is basically a pair of a locale and a string localized to that locale. Let's take an example an entity, let's say a book -object. public class Book{ @OneToMany private List<LocalizedString> names; @OneToMany private List<LocalizedString> description; //and so on... } When a user asks for a list of books, it does a query to get all the books, fetches the name and description of every book in the locale the user has selected to run the app in, and displays it back to the user. This works but it is a major performance issue. For the moment hibernate makes one query to fetch all the books, and after that it goes through every single object and asks hibernate for the localized strings for that specific object, resulting in a "n+1 select problem". Fetching a list of 50 entities produces about 6000 rows of sql commands in my server log. I tried making the collections eager but that lead me to the "cannot simultaneously fetch multiple bags"-issue. Then I tried setting the fetch strategy on the collections to subselect, hoping that it would do one query for all books, and after that do one query that fetches all LocalizedStrings for all the books. Subselects didn't work in this case how i would have hoped and it basically just did exactly the same as my first case. I'm starting to run out of ideas on how to optimize this. So in short, what fetching strategy alternatives are there when you are fetching a collection and every element in that collection has one or multiple collections in itself, which has to be fetch simultaneously.

    Read the article

  • Changing the Hibernate 3 settings

    - by Bogdanel
    I use Hibernate3 and Hibernate Tools 3.2.4 to generate hbm.xml and java files and I want to use List instead of HashSet(...). I've tried to modify the hbm.xml files, putting list instead of set. Is there any way to specify to hibernate tools that I want to generate automatically a list not a HashSet? This is an exemple: Java class public class Test implements java.io.Serializable { private Long testId; private Course course; private String testName; private Set<Question> questions = new HashSet<Question>( 0 ); } Test.hbm.xml: <set name="questions" inverse="true" lazy="true" table="questions" fetch="select"> <key> <column name="test_id" not-null="true" /> </key> <one-to-many class="com.app.objects.Question" /> ... </set> I thought that I could find a clue in the "reveng.xml" file, but I failed.

    Read the article

  • Hibernate Exception Fixed By Alt+Tab

    - by Lee Theobald
    Hi all, I've got a very curious problem in Hibernate that I would like some opinions on. In my code if I do the following: Go to page A Click a link on page A to be taken to page B Click on data item on page B Exception thrown I get an error telling me: failed to lazily initialize a collection of role: XYZ, no session or session was closed Fair enough. But when I do the same thing but add an alt+tab in the middle, everything is fine. E.g. Go to page A Click a link on page A to be taken to page B Hit ALt+Tab to switch to another application Hit ALt+Tab to switch back to the web browser Click on data item on page B Everything is fine. I'm a little confused as to how switching focus from my application makes it act as I want it to. Does anyone have any light to shine on the subject? I don't think it's a locking issue as even if I do the second set of steps quicker than the first, still no error. It's a Seam application using Hibernate 3.3.2.GA & 3.4.0.GA.

    Read the article

  • Hibernate Session flush behaviour [ and Spring @Transactional ]

    - by EugeneP
    I use Spring and Hibernate in a web-app, SessionFactory is injected into a DAO bean, and then this DAO is used in a Servlet through webservicecontext. DAO methods are transactional, inside one of the methods I use ... getCurrentSession().save(myObject); One servlet calls this method with an object passed. The update seems to not be flushed at once, it takes about 5 seconds to see the changes in the database. The servlet's method in which that DAO's update method is called, takes a fraction of second to complete. After the @Transactional method of DAO is completed, flushing may NOT happen ? It does not seem to be a rule [ I already see it ]. Then the question is this: what to do to force the session to flush after every DAO method? It may not be a good thing to do, but talking about a Service layer, some methods must end with immediate flush, and Hibernate Session behavior is not predictable. So what to do to guarantee that my @Transactional method persists all the changes after the last line of that method code? getCurrentSession().flush() is the only solution? p.s. I read somewhere that @Transactional IS ASSOCIATED with a DB Transaction. Method returns, transaction must be committed. I do not see this happens.

    Read the article

  • Catch hibernate exceptions with errorpage handler?

    - by membersound
    I'm catching all exceptions within: java.lang.Throwable /page.xhtml java.lang.Error /page.xhtml But what If I get eg a hibernate ex: org.hibernate.exception.ConstraintViolationException Do I have to define error-pages for EVERY maybe occuring exception? Can't I just say "catch every exception"? Update Redirect on a 404 works. But on a throwable does not! <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.xhtml</location> </error-page> <error-page> <error-code>404</error-code> <location>/error.xhtml</location> </error-page>

    Read the article

  • Hibernate many-to-one - bad usage?

    - by DaveA
    Just trying out Hibernate (with Annotations) and I'm having problems with my mappings. I have two entity classes, AudioCD and Artist. @Entity public class AudioCD implements CatalogItem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String title; @ManyToOne(cascade = { CascadeType.ALL }, optional = false) private Artist artist; .... } @Entity @Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }) }) public class Artist { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(nullable = false) private String name; ..... } I get AudioCD objects from an external source. When I try to persist the AudioCD the Artist gets persisted as well, just like I want to happen. If I try persisting another different CD, but Artist already exists I get errors due to constraint violations. I want Hibernate to recognise that the Artist already exists and shouldn't be inserted again. Can this be done via annotations? Or do I have to manage the persistence of the AudioCD and Artist seperately?

    Read the article

  • hibernate empty collection in component

    - by Jurgen H
    I have a component mapped using Hibernate. If all fields in the component in the database are null, the component itself is set to null by hibernate. This is the expected behavior and also what I need. The problem I have, is that when I add a bag to that component, the bag is initialized to an empty list. This means the component has a non null value... resulting in the component being created. Any idea how to fix this? <class name="foo.bar.Entity" table="Entity"> <id name="id" column="id"> <generator class="native" /> </id> <property name="departure" column="departure_time" /> <property name="arrival" column="arrival_time" /> <component name="statistics"> <bag name="linkStatistics" lazy="false" cascade="all" > <key column="entity_id" not-null="true" /> <one-to-many class="foo.bar.LinkStatistics" /> </bag> <property name="loggedTime" column="logged_time" /> ... </component> A criteria with Restirctions.isNull("statistics") does return the expected values.

    Read the article

  • Hibernate CreateSQL Query Problem

    - by Shaded
    Hello All I'm trying to use hibernates built in createsql function but it seems that it doesn't like the following query. List =hibernateSession.createSQLQuery("SELECT number, location FROM table WHERE other_number IN (SELECT f.number FROM table2 AS f JOIN table3 AS g on f.number = g.number WHERE g.other_number = " + var + ") ORDER BY number").addEntity(Table.class).list(); I have a feeling it's from the nested select statement, but I'm not sure. The inner select is used elsewhere in the code and it returns results fine. This is my mapping for the first table: <hibernate-mapping> <class name="org.efs.openreports.objects.Table" table="table"> <id name="id" column="other_number" type="java.lang.Integer"> <generator class="native"/> </id> <property name="number" column="number" not-null="true" unique="true"/> <property name="location" column="location" not-null="true" unique="true"/> </class> </hibernate-mapping> And the .java public class Table implements Serializable { private Integer id;//panel_facility private Integer number; private String location; public Table() { } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public void setNumber(Integer number) { this.number = number; } public Integer number() { return number; } public String location() { return location; } public void setLocation(String location) { this.location = location; } } Any suggestions? Edit (Added mapping)

    Read the article

  • hibernate annotation bi-directional mapping

    - by smithystar
    I'm building a web application using Spring framework and Hibernate with annotation and get stuck with a simple mapping between two entities. I'm trying to create a many-to-many relationship between User and Course. I followed one of the Hibernate tutorials and my implementation is as follows: User class: @Entity @Table(name="USER") public class User { private Long id; private String email; private String password; private Set<Course> courses = new HashSet<Course>(0); @Id @GeneratedValue @Column(name="USER_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="USER_EMAIL") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name="USER_PASSWORD") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "USER_COURSE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") }) public Set<Course> getCourses() { return courses; } public void setCourses(Set<Course> courses) { this.courses = courses; } } Course class: @Entity @Table(name="COURSE") public class Course { private Long id; private String name; @Id @GeneratedValue @Column(name="COURSE_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } } The problem is that this implementation only allows me to go one way user.getCourses() What do I need to change, so I can go in both directions? user.getCourses() course.getUsers() Any help would be appreciated.

    Read the article

  • Hibernate 1:M relationship ,row order, constant values table and concurrency

    - by EugeneP
    table A and B need to have 1:M relationship a and b are added during application runtime, so A created, then say 4 B's created. Each B instance has to come in order, so that I could later extract them in the same order as I added them. The app will be a web-app running on Tomcat, so 10 instances may work simultaneously. So my question are: 1) How to preserve inserting order, so that I could extract B instances that A references in the same order as I persisted them. That's tricky, because we add to a Collection and then it gets saved (am I right?). So, it depends on how Hibernate saves it, what if it changes the order in what we added instances? I've seen something like LIST instead of SET when describing relationships, is that what I need? 2) How to add a 3-rd column to B so that I could differentiate the instances, something like SEX(M,F,U) in B table. Do I need a special table, or there's and easy way to describe constants in Hibernate. What do you recommend? 3) Talking about concurrency, what methods do you recommend to use? There should be no collisions in the db and as you see, there might easily be some if rows are not inserted (PK added) right where it is invoked without delays ?

    Read the article

  • How to use JOIN using Hibernate's session.createSQLQuery()

    - by javauser71
    Hi All, I have two Entity (tables) - Employee & Project. An Employee can have multiple Projects. Project table's CREATOR_ID field refers to Employee table's ID field. Employee entity maintains a list of Project. Using EntityManager following query works fine - "entityManager.createQuery("select e from EmployeeDTO e, ProjectDTO p where p.id = ?1 and p.creator.id=e.id"); But since I have the LAZY association relationship, I get error: "Could not initialize proxy - no Session" if I try to access Project info from Employee entity. This is expected and so I am using Hibernate's Session to create query as shown below. Session session = HibernateUtil.getSessionFactory().openSession(); org.hibernate.Query q = session.createSQLQuery("SELECT E FROM EMPLOYEE_TAB E, PROJECT_TAB P WHERE P.ID = " + projectId + " AND P.CREATOR_ID = E.ID") .addEntity("EmployeeDTO ", EmployeeDTO.class) .addEntity("ProjectDTO", ProjectDTO.class); But I get error like: "Column 'E' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification..." Can anyone suggest what will be the right JOIN syntax for such case? If I use ("SELECT * FROM EMPLOYEE_TAB E, ........") - it gives other error: "java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.im.server.dto.EmployeeDTO". Thanks in advance.

    Read the article

  • Optional parameters with named query in Hibernate?

    - by Ickster
    Is there any way to specify optional parameters (such as when search parameters are provided from a form and not all parameters are required) in a named query when using Hibernate? I'm using a native SQL query, but the question is probably applicable to named HQL queries as well. I'm pretty sure the answer to this is 'no', but I haven't find the definitive answer in the documentation yet.

    Read the article

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