Search Results

Search found 98 results on 4 pages for 'manytomany'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • django sort by manytomany relationship

    - by Marconi
    I have the following model: class Service(models.Model): ratings = models.ManyToManyField(User) Now if I wanna get all the service with ratings sorted in descending order I did something: services_list = Service.objects.filter(ratings__gt=0).distinct() services_list = list(services_list) services_list.sort(key=lambda service: service.ratings.all().count(), reverse=True) As you can see its a three step process and I don't feel right about this. Anybody who knows a better way to do this?

    Read the article

  • Django ManyToMany Membership errors making associations

    - by jmitchel3
    I'm trying to have a "member admin" in which they have hundreds of members in the group. These members can be in several groups. Admins can remove access for the member ideally in the view. I'm having trouble just creating the group. I used a ManytoManyField to get started. Ideally, the "member admin" would be able to either select existing Users OR it would be able to Add/Invite new ones via email address. Here's what I have: #views.py def membership(request): group = Group.objects.all().filter(user=request.user) GroupFormSet = modelformset_factory(Group, form=MembershipForm) if request.method == 'POST': formset = GroupFormSet(request.POST, request.FILES, queryset=group) if formset.is_valid(): formset.save(commit=False) for form in formset: form.instance.user = request.user formset.save() return render_to_response('formset.html', locals(), context_instance=RequestContext(request)) else: formset= GroupFormSet(queryset=group) return render_to_response('formset.html', locals(), context_instance=RequestContext(request)) #models.py class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(User, related_name='community_members', through='Membership') user = models.ForeignKey(User, related_name='community_creator', null=True) def __unicode__(self): return self.name class Membership(models.Model): member = models.ForeignKey(User, related_name='user_membership', blank=True, null=True) group = models.ForeignKey(Group, related_name='community_membership', blank=True, null=True) date_joined = models.DateField(auto_now=True, blank=True, null=True) class Meta: unique_together = ('member', 'group') Any ideas? Thank you for your help.

    Read the article

  • Filtering across two ManyToMany fields

    - by KVISH
    I have a User model and an Event model. I have the following for both: class Event(models.Model): ... timestamp = models.DateTimeField() organization_map = models.ManyToManyField(Organization) class User(AuthUser): ... subscribed_orgs = models.ManyToManyField('Organization') I want to find all events that were created in a certain timeframe and find the users who are subscribed to those organizations. I know how to write SQL for this (it's very easy), but whats the pythonic way of doing this using Django ORM? I'm trying as per below: orgs = Organization.objects.all() events = Event.objects.filter(timestamp__gt=min_time) # Min time is the time I want to start from events = events.filter(organization_map__in=orgs) But from there, how do I map to users who have that organization as a subscription? I'm trying to map it like so: users = User.objects.filter(subscribed_orgs__in=...

    Read the article

  • Fluent NHibernate Self Referencing Many To Many

    - by Jeremy
    I have an entity called Books that can have a list of more books called RelatedBooks. The abbreviated Book entity looks something likes this: public class Book { public virtual long Id { get; private set; } public virtual IList<Book> RelatedBooks { get; set; } } Here is what the mapping looks like for this relationship HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks") .Cascade.SaveUpdate(); Here is a sample of the data that is then generated in the RelatedBooks table: BookId RelatedBookId 1 2 1 3 The problem happens when I Try to delete a book. If I delete the book that has an ID of 1, everything works ok and the RelatedBooks table has the two corresponding records removed. However if I try to delete the book with an ID of 3, I get the error "The DELETE statement conflicted with the REFERENCE constraint "FK5B54405174BAB605". The conflict occurred in database "Test", table "dbo.RelatedBooks", column 'RelatedBookId'". Basically what is happening is the Book cannot be deleted because the record in the RelatedBooks table that has a RelatedBookId of 3 is never deleted. How do I get that record to be deleted when I delete a book? EDIT After changing the Cascade from SaveUpdate() to All(), the same problem still exists if I try to delete the Book with an ID of 3. Also with Cascade set to All(), if delete the Book with and ID of 1, then all 3 books (ID's: 1, 2 and 3) are deleted so that won't work either. Looking at the SQL that is executed when the Book.Delete() method is called when I delete the Book with an ID of 3, it looks like the SELECT statement is looking at the wrong column (which I assume means that the SQL DELETE statment would make the same mistake, therefore never removing that record). Here is the SQL for the RelatedBook SELECT relatedboo0_.BookId as BookId3_ , relatedboo0_.RelatedBookId as RelatedB2_3_ , book1_.Id as Id14_0_ FROM RelatedBooks relatedboo0_ left outer join [Book] book1_ on relatedboo0_.RelatedBookId=book1_.Id WHERE relatedboo0_.BookId=3 The WHERE statment should look something like this for thie particular case: WHERE relatedboo0_.RelatedBookId = 3 SOLUTION Here is what I had to do to get it working for all cases Mapping: HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks"); Code: var book = currentSession.Get<Book>(bookId); if (book != null) { //Remove all of the Related Books book.RelatedBooks.Clear(); //Get all other books that have this book as a related book var booksWithRelated = currentSession.CreateCriteria<Book>() .CreateAlias("RelatedBooks", "br") .Add(Restrictions.Eq("br.Id", book.Id)) .List<Book>(); //Remove this book as a Related Book for all other Books foreach (var tempBook in booksWithRelated) { tempBook.RelatedBooks.Remove(book); tempBook.Save(); } //Delete the book book.Delete(); }

    Read the article

  • How make this special many2many fields validation using Django ORM?

    - by e-satis
    I have the folowing model: class Step(models.Model): order = models.IntegerField() latitude = models.FloatField() longitude = models.FloatField() date = DateField(blank=True, null=True) class Journey(models.Model): boat = models.ForeignKey(Boat) route = models.ManyToManyField(Step) departure = models.ForeignKey(Step, related_name="departure_of", null=True) arrival = models.ForeignKey(Step, related_name="arrival_of", null=True) I would like to implement the following check: # If a there is less than one step, raises ValidationError. routes = tuple(self.route.order_by("date")) if len(routes) <= 1: raise ValidationError("There must be at least two setps in the route") # save the first and the last step as departure and arrival self.departure = routes[0] self.arrival = routes[-1] # departure and arrival must at least have a date if not (self.departure.date or self.arrival.date): raise ValidationError("There must be an departure and an arrival date. " "Please set the date field for the first and last Step of the Journey") # departure must occurs before arrival if not (self.departure.date > self.arrival.date): raise ValidationError("Departure must take place the same day or any date before arrival. " "Please set accordingly the date field for the first and last Step of the Journey") I tried to do that by overloading save(). Unfortunately, Journey.route is empty in save(). What's more, Journey.id doesn't exists yet. I didn't try django.db.models.signals.post_save but suppose it will fail because Journey.route is empty as well (when does this get filled anyway?). I see a solution in django.db.models.signals.m2m_changed but there are a lot of steps (thousands), and I want to avoid to perform an operation for every single of them.

    Read the article

  • Order in many to many relation in Django model

    - by Pietro Speroni
    I am writing a small website to store the papers I have written. The relation papers<- author is important, but the order of the name of the authors (which one is First Author, which one is second order, and so on) is also important. I am just learning Django so I don't know much. In any case so far I have done: from django.db import models class author(models.Model): Name = models.CharField(max_length=60) URLField = models.URLField(verify_exists=True, null=True, blank=True) def __unicode__(self): return self.Name class topic(models.Model): TopicName = models.CharField(max_length=60) def __unicode__(self): return self.TopicName class publication(models.Model): Title = models.CharField(max_length=100) Authors = models.ManyToManyField(author, null=True, blank=True) Content = models.TextField() Notes = models.TextField(blank=True) Abstract = models.TextField(blank=True) pub_date = models.DateField('date published') TimeInsertion = models.DateTimeField(auto_now=True) URLField = models.URLField(verify_exists=True,null=True, blank=True) Topic = models.ManyToManyField(topic, null=True, blank=True) def __unicode__(self): return self.Title This work fine in the sense that I now can define who the authors are. But I cannot order them. How should I do that? Of course I could add a series of relations: first author, second author,... but it would be ugly, and would not be flexible. Any better idea? Thanks

    Read the article

  • Java many to many association map

    - by Raphael Jolivet
    Hi, I have to classes, ClassA and ClassB and a "many to many" AssociationClass. I want to use a structure to hold the associations between A and B such as I can know, for each instance of A or B, which are their counterparts. I thought of using a Hashmap, with pair keys: Hasmap<Pair<ClassA, ClassB>, AssociationClass> associations; This way, I can add and remove an association between two instances of ClassA and ClassB, and I can query a relation for two given instances. However, I miss the feature of getting all associations defined for a given instance of ClassA or ClassB. I could do it by brute force and loop over all keys of the map to search for associations between a given instance, but this is inefficient and not elegant. Do you know of any data structure / free library that enables this ? I don't want to reinvent the wheel. Thanks in advance for your help, Raphael NB: This is not a "database" question. These objects are pure POJO used for live computation, I don't need persistence stuff.

    Read the article

  • Many-To-Many Query with Linq-To-NHibernate

    - by rjygraham
    Ok guys (and gals), this one has been driving me nuts all night and I'm turning to your collective wisdom for help. I'm using Fluent Nhibernate and Linq-To-NHibernate as my data access story and I have the following simplified DB structure: CREATE TABLE [dbo].[Classes]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](100) NOT NULL, [StartDate] [datetime2](7) NOT NULL, [EndDate] [datetime2](7) NOT NULL, CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED ( [Id] ASC ) CREATE TABLE [dbo].[Sections]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [ClassId] [bigint] NOT NULL, [InternalCode] [varchar](10) NOT NULL, CONSTRAINT [PK_Sections] PRIMARY KEY CLUSTERED ( [Id] ASC ) CREATE TABLE [dbo].[SectionStudents]( [SectionId] [bigint] NOT NULL, [UserId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_SectionStudents] PRIMARY KEY CLUSTERED ( [SectionId] ASC, [UserId] ASC ) CREATE TABLE [dbo].[aspnet_Users]( [ApplicationId] [uniqueidentifier] NOT NULL, [UserId] [uniqueidentifier] NOT NULL, [UserName] [nvarchar](256) NOT NULL, [LoweredUserName] [nvarchar](256) NOT NULL, [MobileAlias] [nvarchar](16) NULL, [IsAnonymous] [bit] NOT NULL, [LastActivityDate] [datetime] NOT NULL, PRIMARY KEY NONCLUSTERED ( [UserId] ASC ) I omitted the foreign keys for brevity, but essentially this boils down to: A Class can have many Sections. A Section can belong to only 1 Class but can have many Students. A Student (aspnet_Users) can belong to many Sections. I've setup the corresponding Model classes and Fluent NHibernate Mapping classes, all that is working fine. Here's where I'm getting stuck. I need to write a query which will return the sections a student is enrolled in based on the student's UserId and the dates of the class. Here's what I've tried so far: 1. var sections = (from s in this.Session.Linq<Sections>() where s.Class.StartDate <= DateTime.UtcNow && s.Class.EndDate > DateTime.UtcNow && s.Students.First(f => f.UserId == userId) != null select s); 2. var sections = (from s in this.Session.Linq<Sections>() where s.Class.StartDate <= DateTime.UtcNow && s.Class.EndDate > DateTime.UtcNow && s.Students.Where(w => w.UserId == userId).FirstOrDefault().Id == userId select s); Obviously, 2 above will fail miserably if there are no students matching userId for classes the current date between it's start and end dates...but I just wanted to try. The filters for the Class StartDate and EndDate work fine, but the many-to-many relation with Students is proving to be difficult. Everytime I try running the query I get an ArgumentNullException with the message: Value cannot be null. Parameter name: session I've considered going down the path of making the SectionStudents relation a Model class with a reference to Section and a reference to Student instead of a many-to-many. I'd like to avoid that if I can, and I'm not even sure it would work that way. Thanks in advance to anyone who can help. Ryan

    Read the article

  • Django Many-to-Many Question

    - by DZ
    My questions seems like a common problem that when I have seen any questions on it is never really asked right or not answered. So Im going to try to get the question right, and maybe someone knows how to resolve the issue, or correct my understanding. The problem: When you have a many-to-many relation ship (related_name not through) and you are trying to use the admin interface you are required to input one of the rleationships even though it does not have to exsist for you to create the first entry. Meaning you have to assign a group to an event to create the group. Wow that sounds complicated. So I can see why the question is not getting answered. Lets try the non code explanation example... First and important versions: Django 1.1.1 Phython 2.6 So I have a model where I created a many-to-many realtionship and Im using the related_name Im creating an app that is an event organizer, for simplicty lets say events although they could be anytype). For this first post Im going to stay away from the code and just try to explain. A few keys: (explaining comment) ** - many-to-many So in the model we have 1) The Main Event (this is main model) 2) Groups (link to events and their can be many events for a group) a) Events** I have simplified this example a little becuase I recognize that what does it matter. Just create the event first... But there are specific varations where that will not work. What the many-to-many related_name does it created another table with the indecies of the two other tables. Nothing says that this extra table HAS to be populated. Becuase if I look in the database and work within myPHPadmin I can create a group with out registering an event, since the connection between the two is a seperate table the DB does not care. How do I make the admin interface this realize it? Ok I know thats a lot so I hope I have explained it clearly. Thank you anyone for your comments/thoughts/advice

    Read the article

  • How do I search for an array of values in a many to many relation?

    - by Kristian Gudal
    Hey I have a problem with my LINQ to Entity model many to mant relation. I am new to both C# and LINQ, so bear with me. I have a model containing pictures and tags, where each picture can have many tags, and each tag can be on many pictures. In the db there is a normal relation table, but in the object model I see it as picture.tags (as a list) and tag.pictures (as a list). A search query contains several tags, and the result of the search is to contain all pictures that are tagged with all the tags (but maybe more) I have searched for. The number of tags to search for is not fixed. How can this best be done?

    Read the article

  • How to insert rows in a many-to-many relationship

    - by GSound
    Hello, I am having an issue trying to save into an intermediate table. I am new on Rails and I have spent a couple of hours on this but can't make it work, maybe I am doing wrong the whole thing. Any help will be appreciated. =) The app is a simple book store, where a logged-in user picks books and then create an order. This error is displayed: NameError in OrderController#create uninitialized constant Order::Orderlist These are my models: class Book < ActiveRecord::Base has_many :orderlists has_many :orders, :through => :orderlists end class Order < ActiveRecord::Base belongs_to :user has_many :orderlists has_many :books, :through => :orderlists end class OrderList < ActiveRecord::Base belongs_to :book belongs_to :order end This is my Order controller: class OrderController < ApplicationController def add if session[:user] book = Book.find(:first, :conditions => ["id = #{params[:id]}"]) if book session[:list].push(book) end redirect_to :controller => "book" else redirect_to :controller => "user" end end def create if session[:user] @order = Order.new if @order.save session[:list].each do |b| @order.orderlists.create(:book => b) # <-- here is my prob I cant make it work end end end redirect_to :controller => "book" end end Thnx in advance! Manuel

    Read the article

  • How do I migrate a ManyToOne to a ManyToMany relationship in Hibernate?

    - by spderosso
    I have a instance field of a class X that is mapped using Hibernate as a Many to One relationship. E.g: public class X{ ... @ManyToOne(optional=false) private Y iField; ... } That is correctly working with a particular schema. I know want to change this instance field iField to a List and a Many to Many relationship. public class X{ ... @ManyToMany(optional=false) private List<Y> iField; ... } What steps should I follow? Do I have to change the schema? in which way? In case you need more info let me know. Thanks!

    Read the article

  • How to show raw_id value of a ManyToMany relation in the Django admin?

    - by luc
    Hello, I have an app using raw_id on both ForeignKeyField and ManyToManyField. The admin displays the value of the foreign key on the right of the edit box. Unfortunatey, it doesn't work with ManyToMany. I've checked the code and I think that it is the normal behavior. However I would like to know if someone has an easy tip to change this behavior? Thanks in advance Update: I've tried to subclass the ManyToManyRawIdWidget but I don't know how to say that the raw_id_fields should use my custom widget. formfield_overrides doesn't seem to work with raw_id fields

    Read the article

  • How Can I Populate Default Form Data with a ManyToMany Field?

    - by b14ck
    Ok, I've been crawling google and Django documentation for over 2 hours now (as well as the IRC channel on freenode), and haven't been able to figure this one out. Basically, I have a model called Room, which is displayed below: class Room(models.Model): """ A `Partyline` room. Rooms on the `Partyline`s are like mini-chatrooms. Each room has a variable amount of `Caller`s, and usually a moderator of some sort. Each `Partyline` has many rooms, and it is common for `Caller`s to join multiple rooms over the duration of their call. """ LIVE = 0 PRIVATE = 1 ONE_ON_ONE = 2 UNCENSORED = 3 BULLETIN_BOARD = 4 CHILL = 5 PHONE_BOOTH = 6 TYPE_CHOICES = ( ('LR', 'Live Room'), ('PR', 'Private Room'), ('UR', 'Uncensored Room'), ) type = models.CharField('Room Type', max_length=2, choices=TYPE_CHOICES) number = models.IntegerField('Room Number') partyline = models.ForeignKey(Partyline) owner = models.ForeignKey(User, blank=True, null=True) bans = models.ManyToManyField(Caller, blank=True, null=True) def __unicode__(self): return "%s - %s %d" % (self.partyline.name, self.type, self.number) I've also got a forms.py which has the following ModelForm to represent my Room model: from django.forms import ModelForm from partyline_portal.rooms.models import Room class RoomForm(ModelForm): class Meta: model = Room I'm creating a view which allows administrators to edit a given Room object. Here's my view (so far): def edit_room(request, id=None): """ Edit various attributes of a specific `Room`. Room owners do not have access to this page. They cannot edit the attributes of the `Room`(s) that they control. """ room = get_object_or_404(Room, id=id) if not room.is_owner(request.user): return HttpResponseForbidden('Forbidden.') if is_user_type(request.user, ['admin']): form_type = RoomForm elif is_user_type(request.user, ['lm']): form_type = LineManagerEditRoomForm elif is_user_type(request.user, ['lo']): form_type = LineOwnerEditRoomForm if request.method == 'POST': form = form_type(request.POST, instance=room) if form.is_valid(): if 'owner' in form.cleaned_data: room.owner = form.cleaned_data['owner'] room.save() else: defaults = {'type': room.type, 'number': room.number, 'partyline': room.partyline.id} if room.owner: defaults['owner'] = room.owner.id if room.bans: defaults['bans'] = room.bans.all() ### this does not work properly! form = form_type(defaults, instance=room) variables = RequestContext(request, {'form': form, 'room': room}) return render_to_response('portal/rooms/edit.html', variables) Now, this view works fine when I view the page. It shows all of the form attributes, and all of the default values are filled in (when users do a GET)... EXCEPT for the default values for the ManyToMany field 'bans'. Basically, if an admins clicks on a Room object to edit, the page they go to will show all of the Rooms default values except for the 'bans'. No matter what I do, I can't find a way to get Django to display the currently 'banned users' for the Room object. Here is the line of code that needs to be changed (from the view): defaults = {'type': room.type, 'number': room.number, 'partyline': room.partyline.id} if room.owner: defaults['owner'] = room.owner.id if room.bans: defaults['bans'] = room.bans.all() ### this does not work properly! There must be some other syntax I have to use to specify the default value for the 'bans' field. I've really been pulling my hair out on this one, and would definitely appreciate some help. Thanks!

    Read the article

  • Django. Invalid keyword argument for this function. ManyToMany

    - by sagem_tetra
    I have this error: 'people' is an invalid keyword argument for this function class Passage(models.Model): name= models.CharField(max_length = 255) who = models.ForeignKey(UserProfil) class UserPassage(models.Model): passage = models.ForeignKey(Passage) people = models.ManyToManyField(UserProfil, null=True) class UserProfil(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=50) I try: def join(request): user = request.user user_profil = UserProfil.objects.get(user=user) passage = Passage.objects.get(id=2) #line with error up = UserPassage.objects.create(people= user_profil, passage=passage) return render_to_response('thanks.html') How to do correctly? Thanks!

    Read the article

  • JPA : many-to-many - only one foreign key in the association table

    - by Julien
    Hi, I mapped two classes in a ManyToMany association with these annotations : @Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public abstract class TechnicalItem extends GenericBusinessObject implements Resumable{ @SequenceGenerator(name="TECHNICAL_ITEM_ID_GEN", sequenceName="TECHNICAL_ITEM_ID_SEQ") @Id @Column(name = "\"ID\"", nullable = false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TECHNICAL_ITEM_ID_GEN") private int id; @ManyToMany(mappedBy = "referencePerformanceItems", fetch=FetchType.LAZY) private List testingRates; } @Entity @DiscriminatorValue("T") public class TestingRate extends Rate { @ManyToMany(fetch=FetchType.LAZY) @JoinTable(name="ecc.\"TESTING_RATE_TECHNICAL_ITEM\"", joinColumns = {@JoinColumn(name = "\"TESTING_RATE_ID\"")}, inverseJoinColumns = {@JoinColumn(name = "\"TECHNICAL_ITEM_ID\"")}) //@ManyToMany(mappedBy = "testingRates", fetch=FetchType.LAZY) private List referencePerformanceItems; } The sql generated for the association table creation is : create table ecc."TESTING_RATE_TECHNICAL_ITEM" ( "TESTING_RATE_ID" int4 not null, "TECHNICAL_ITEM_ID" int4 not null ); alter table ecc."TESTING_RATE_TECHNICAL_ITEM" add constraint FKC5D64DF6A2FE2698 foreign key ("TESTING_RATE_ID") references ecc."RATE"; There is no mention of the second foreign key "TECHNICAL_ITEM_ID" (the second part of the composite foreign key which should be in the association table). Is it a normal behaviour ? What should I do in the mapping if I want my 2 columns are 2 foreign keys referencing the primary keys of my 2 concerned tables. I use a PostGreSQL database and Hibernate as JPA provider. Thanks, Julien

    Read the article

  • SQLAlchemy & Complex Queries

    - by user356594
    I have to implement ACL for an existing application. So I added the a user, group and groupmembers table to the database. I defined a ManyToMany relationship between user and group via the association table groupmembers. In order to protect some ressources of the app (i..e item) I added a additional association table auth_items which should be used as an association table for the ManyToMany relationship between groups/users and the specific item. item has following columns: user_id -- user table group_id -- group table item_id -- item table at least on of user_id and group_id columns are set. So it's possible to define access for a group or for a user to a specific item. I have used the AssociationProxy to define the relationship between users/groups and items. I now want to display all items which the user has access to and I have a really hard time doing that. Following criteria are used: All items which are owned by the user should be shown (item.owner_id = user.id) All public items should be shown (item.access = public) All items which the user has access to should be shown (auth_item.user_id = user.id) All items which the group of the user has access to should be shown. The first two criteria are quite straightforward, but I have a hard time doing the 3rd one. Here is my approach: clause = and_(item.access == 'public') if user is not None: clause = or_(clause,item.owner == user,item.users.contains(user),item.groups.contains(group for group in user.groups)) The third criteria produces an error. item.groups.contains(group for group in user.groups) I am actually not sure if this is a good approach at all. What is the best approach when filtering manytomany relationships? How I can filter a manytomany relationship based on another list/relationship? Btw I am using the latest sqlalchemy (6.0) and elixir version Thanks for any insights.

    Read the article

  • Django Show M2M field in both model forms

    - by John
    Hi I am using the forms.ModelForm to create my form. I want to be able to show the manytomany field in both model forms, how do I do this? If the manytomany relationship is defined in the model it is fine and just appears but if it is not in the model (but is still linked via the other model) it does not appear. Hope this makes sense. How can I make it show up? Thanks

    Read the article

  • many to many and integrity when saving the null

    - by user369759
    I have two classes Software, Tag - they are related by ManyToMany. We CAN NOT create Software without putting the Tag to it. I want to write a test which check that: @Test public void createSoftwareWithNullTags() { List<Tag> tags = null; Software software = new Software("software1", "description1", tags); try { software.save(); fail("tags should not be null"); } catch (Exception ex) { // NEVER COME HERE !!! } } So, this test fails. I guess it is not good test for that case - because it even do not try to SAVE data to SOFTWARE_TAG table. Of course i could do validation manually but i want implement it with hibernate, using some annotation or something. Is it possible? Or how would you do this? My entities: @Entity public class Tag extends Model { public String title; public Tag(String title) { this.title = title; } @ManyToMany( cascade = {CascadeType.ALL}, mappedBy = "tags", targetEntity = Software.class ) public List<Software> softwares; } @Entity public class Software extends Model { public String title; public String description; @ManyToOne(optional = false) public Author author; @ManyToMany(cascade = CascadeType.ALL) @JoinTable( name = "SOFTWARE_TAG", joinColumns = @JoinColumn(name = "Software_id"), inverseJoinColumns = @JoinColumn(name = "Tag_id") ) public List<Tag> tags; public Software(String title, String description, Author author, List<Tag> tags) { this.title = title; this.description = description; this.author = author; this.tags = tags; } }

    Read the article

  • How should I implement Transaction database EJB 3.0

    - by JamesBoyZ
    In the CustomerTransactions entity, I have the following field to record what the customer bought: @ManyToMany private List<Item> listOfItemsBought; When I think more about this field, there's a chance it may not work because merchants are allowed to change item's information (e.g. price, discount, etc...). Hence, this field will not be able to record what the customer actually bought when the transaction occurred. At the moment, I can only think of 2 ways to make it work. I will record the transaction details into a String field. I feel that this way would be messy if I need to extract some information about the transaction later on. Whenever the merchant changes an item's information, I will not update directly to that item's fields. Instead, I will create another new item with all the new information and keep the old item untouched. I feel that this way is better because I can easily extract information about the transaction later on. However, the bad side is that my Item table may contain a lot of rows. I'd be very grateful if someone could give me an advice on how I should tackle this problem. UPDATE: I'd like to add more information about the current design. public class Customer implements Serializable { @OneToMany private List<CustomerTransactions> listOfTransactions; } public class CustomerTransactions implements Serializable { @ManyToMany private List<Item> listOfItemsBought; } public class Merchant implements Serializable { @OneToMany private List<Item> listOfSellingItems; }

    Read the article

  • JPQL check many-to-many relationship

    - by Juriy
    Just a quick question: There's the entity (for example User) who is connected with the ManyToMany relationship to the same entity (for example this relation describes "friendship" and it is symmetric). What is the fastest way in terms of execution time to check if User A is a "friend" of user B? The "dumb" way would be to fetch whole List and then check if user exists there but that's obviously the overhead. I'm using JPA 2 Here's the sample code: @Entity @Table(name="users") public class UserEntity { @ManyToMany(fetch = FetchType.LAZY) private List<UserEntity> friends; .... }

    Read the article

  • How to solve lazy initialization exception using JPA and Hibernate as provider

    - by rupertin
    I am working on a project for a customer who wants to use lazy initialization. They always get "lazy initialization exception" when mapping classes with the default lazy loading mode. @JoinTable(name = "join_profilo_funzionalita", joinColumns = {@JoinColumn(name = "profilo_id", referencedColumnName = "profilo_id")}, inverseJoinColumns = {@JoinColumn(name = "funzionalita_id", referencedColumnName = "funzionalita_id")}) //@ManyToMany(fetch=FetchType.EAGER) - no exceptions if uncommented @ManyToMany private Collection<Funzionalita> funzionalitaIdCollection; Is there a standard pattern using JPA classes to avoid this error? Snippets are welcome, thanks a lot for your time.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >